API Fixed response

Feb 03, 2024

Simplifying API Responses with AutoWrapper.Core in .NET Core.

Handling API responses effectively is a crucial aspect of building robust and user-friendly applications. In .NET Core applications, the AutoWrapper.Core library comes to the rescue, providing a streamlined way to structure and standardize API responses. In this blog post, we'll explore how to use AutoWrapper.Core to create fixed responses for different status codes in your API.

Firstly, you'll need to install the AutoWrapper.Core NuGet package. Add the following line to your project's .csproj file:

<PackageReference Include="AutoWrapper.Core" Version="4.5.1" />

This package simplifies the process of handling API responses and ensures a consistent format for success, error, and data messages.
 

Example: Login Method

Let's consider a common scenario, the login method, where we want to ensure fixed responses for both successful and unsuccessful attempts.

[HttpPost("Login")]
public async Task<ApiResponse> Login([FromBody] Login model)
{
    var user = await _userService.GetUserByName(model.UserName);
    if (user != null && await _userService.CheckUserPassword(user, model.Password))
    {
        var userResponse = await _tokenService.GenerateToken(user);
        return new ApiResponse(message: "Login Successfully.", result: userResponse, statusCode: 200);
    }

    return new ApiResponse(message: "Invalid Credential.", result: null, statusCode: 401);
}


In this example, we're using AutoWrapper.Core's ApiResponse class to encapsulate our responses.

For a successful login attempt (status code 200), we return a positive message along with the user response.

In case of invalid credentials (status code 401), an appropriate error message is provided.

ApiResponse Class

Now, let's take a closer look at the ApiResponse class from AutoWrapper.Core:

namespace AutoWrapper.Wrappers;

public class ApiResponse
{
    public string Version { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    public int StatusCode { get; set; }

    public string Message { get; set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    public bool? IsError { get; set; }

    public object ResponseException { get; set; }

    public object Result { get; set; }

    [JsonConstructor]
    public ApiResponse(string message, object result = null, int statusCode = 200, string apiVersion = "1.0.0.0")
    {
        StatusCode = statusCode;
        Message = message;
        Result = result;
        Version = apiVersion;
    }

    public ApiResponse(object result, int statusCode = 200)
    {
        StatusCode = statusCode;
        Result = result;
    }

    public ApiResponse(int statusCode, object apiError)
    {
        StatusCode = statusCode;
        ResponseException = apiError;
        IsError = true;
    }

    public ApiResponse()
    {
    }
}


The ApiResponse class provides flexibility in constructing responses with different components such as the message, result, and status code. It helps maintain a standardized format for all API responses.

Create a Custom Wrapper:

AutoWrapper allows you to create a custom wrapper by implementing the IApiResponse interface. You can create a class that implements this interface to customize the fixed response.

Here's an example:
Create a Custom Wrapper: AutoWrapper allows you to create a custom wrapper by implementing the IApiResponse interface. You can create a class that implements this interface to customize the fixed response. Here's an example:

using AutoWrapper.Wrappers;

public class CustomApiResponse<T> : ApiResponse<T>
{
    public string CustomProperty { get; set; }

    public CustomApiResponse(T result, string customProperty) : base(result)
    {
        CustomProperty = customProperty;
    }
}


Configure AutoWrapper: In your Startup.cs file, configure AutoWrapper to use your custom wrapper. You can do this in the ConfigureServices method:

services.AddAutoWrapper(config =>
{
    config.UseCustomSchema<CustomApiResponse<object>>();
});

Replace CustomApiResponse<object> with the custom wrapper class you created.

Use Custom Wrapper in Controller Actions: Now, you can use your custom wrapper in your controller actions.

For example:

[ApiController]
[Route("api/[controller]")]
public class MyController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        // Your logic here
        var data = new { Message = "Hello, World!" };

        // Use the custom wrapper
        var response = new CustomApiResponse<object>(data, "CustomProperty");

        return Ok(response);
    }
}

Customize the CustomApiResponse according to your needs, and use it in your controller actions.

This way, you can integrate AutoWrapper with other packages and customize the fixed response format in your .NET application.
 

In conclusion, by incorporating AutoWrapper.Core into your .NET Core applications, you can simplify the handling of API responses, making your code more readable, maintainable, and user-friendly. Consider adopting this approach to enhance the overall developer experience and ensure consistency in your API communication.

Himanshu Pranami

About the Author

Himanshu Pranami

I'm working as a Software Developer at MagnusMinds IT Solution. I bring 3+ years of professional experience to the table. My expertise spans a range of technologies, including .NET Framework, .NET Core, MVC, ASP.NET, Entity Framework, ADO.NET, SQL, PostgreSQL, C#, Azure DevOps, and Microservices.