Kemenkeu.ApiWrapper.Core 1.1.0

dotnet add package Kemenkeu.ApiWrapper.Core --version 1.1.0
                    
NuGet\Install-Package Kemenkeu.ApiWrapper.Core -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Kemenkeu.ApiWrapper.Core" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Kemenkeu.ApiWrapper.Core" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="Kemenkeu.ApiWrapper.Core" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Kemenkeu.ApiWrapper.Core --version 1.1.0
                    
#r "nuget: Kemenkeu.ApiWrapper.Core, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Kemenkeu.ApiWrapper.Core@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Kemenkeu.ApiWrapper.Core&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=Kemenkeu.ApiWrapper.Core&version=1.1.0
                    
Install as a Cake Tool

Kemenkeu.ApiWrapper.Core

Kemenkeu.ApiWrapper.Core is a library designed to standardize API responses in .NET applications. It provides a consistent response format, comprehensive exception handling, pagination support, and integrates easily with ASP.NET Core.

Features

  • Standardized API Response: Easily wrap your API responses in a consistent format.
  • Comprehensive Exception Handling: Automatically handle exceptions and return structured error messages with proper HTTP status codes.
  • Custom Exception Types: Pre-built exception types for common scenarios (BadRequest, NotFound, Unauthorized, etc.).
  • Pagination Support: Manage pagination metadata effectively.
  • Global Filters: Automatically apply response formatting to all controllers without additional configuration.
  • Multi-Framework Support: Compatible with .NET Core 3.1, .NET 5.0, .NET 6.0+.

Compatibility

This library supports multiple frameworks:

  • .NET Core 3.1
  • .NET 5.0
  • .NET 6.0 and later

Installation

From NuGet

To install the Kemenkeu.ApiWrapper.Core library, use the following command in your terminal or package manager console:

dotnet add package Kemenkeu.ApiWrapper.Core

Quick Start Guide

1. Configure Services

Add the library to your Startup.cs file in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddKemenkeuApiWrapper();
}

2. Configure Middleware

Enable the global response wrapping and exception handling in the Configure method:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // Add the ApiWrapper middleware (should be early in the pipeline)
    app.UseKemenkeuApiWrapper();
    
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

3. Using Exception Handling in Services

The wrapper now provides comprehensive exception handling. Simply throw exceptions in your services and they will be automatically converted to proper API responses:

public class UserService
{
    public async Task<User> GetUserByEmail(string email)
    {
        if (string.IsNullOrEmpty(email))
        {
            throw new BadRequestException("Email address is required");
        }

        var user = await _repository.GetByEmailAsync(email);
        
        if (user == null)
        {
            // This exact exception will return a 404 response
            throw new NotFoundException("User email tidak ditemukan.");
        }

        return user;
    }
}

4. Available Exception Types

  • BadRequestException (400): For invalid input or business rule violations
  • UnauthorizedException (401): For authentication failures
  • ForbiddenException (403): For authorization failures
  • NotFoundException (404): For resource not found scenarios
  • ConflictException (409): For data conflicts
  • ValidationException (422): For validation failures
  • InternalServerErrorException (500): For internal server errors

5. Controller Usage

Your controllers can now focus on business logic without worrying about response formatting:

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly IUserService _userService;

    public UsersController(IUserService userService)
    {
        _userService = userService;
    }

    [HttpGet("{email}")]
    public async Task<User> GetByEmail(string email)
    {
        // This will automatically return a 404 response if user is not found
        return await _userService.GetUserByEmail(email);
    }

    [HttpPost]
    public async Task<User> CreateUser(CreateUserRequest request)
    {
        // This will automatically return appropriate error responses for validation failures
        return await _userService.CreateUser(request);
    }
}

6. Response Format

All responses follow this consistent format:

{
  "data": { /* your data here */ },
  "isError": false,
  "statusCode": 200,
  "message": "Request was successful.",
  "errors": []
}

Error responses:

{
  "data": null,
  "isError": true,
  "statusCode": 404,
  "message": "User email tidak ditemukan.",
  "errors": [
    "User email tidak ditemukan."
  ]
}

7. Pagination Support

To use pagination, specify pagination metadata on your actions:

[HttpGet]
[PaginatedResponse]
public IActionResult GetPaginatedData(int page = 1, int pageSize = 10)
{
    var data = GetData(page, pageSize);
    return Ok(data); // Pagination metadata will be included in headers
}

8. Disabling the Wrapper

If you need to disable the wrapper for specific actions:

[HttpGet("health")]
[DisableApiWrapper]
public IActionResult Health()
{
    return Ok("Healthy"); // Returns raw response without wrapping
}

Advanced Usage

For detailed examples and advanced usage scenarios, see the Exception Handling Guide.

Contributing

If you would like to contribute to Kemenkeu.ApiWrapper.Core, please fork the repository and submit a pull request. We welcome contributions, bug reports, and feature requests!

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.1 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 276 10/15/2025
1.0.0 284 11/8/2024