Ethik.Utility.Api 1.0.2

dotnet add package Ethik.Utility.Api --version 1.0.2
                    
NuGet\Install-Package Ethik.Utility.Api -Version 1.0.2
                    
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="Ethik.Utility.Api" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Ethik.Utility.Api" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Ethik.Utility.Api" />
                    
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 Ethik.Utility.Api --version 1.0.2
                    
#r "nuget: Ethik.Utility.Api, 1.0.2"
                    
#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 Ethik.Utility.Api@1.0.2
                    
#: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=Ethik.Utility.Api&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Ethik.Utility.Api&version=1.0.2
                    
Install as a Cake Tool

Ethik.Utility.Api NuGet Package (not updated doc)

Overview

The Ethik.Utility.Api NuGet package provides a set of utilities for handling API tasks in .NET applications. It includes error handling, response generation, and useful extensions

Features

  • API Responses: Consistent API response format for success and failure scenarios.
  • Service Collection Extensions:
    • Error Caching:
      • AddErrorConfig: Adds and initializes ApiErrorConfigService to manage error responses with configuration from a JSON file.
    • Global Exception Handling:
      • AddGlobalExceptionHandler: Adds global exception handling and ProblemDetails services for standardized error responses.
    • Swagger with JWT:
      • AddSwaggerGenWithAuth: Configures Swagger for API documentation with JWT bearer token authentication support.

Installation

You can install the package via NuGet Package Manager or by running the following command in the Package Manager Console:

Install-Package Ethik.Utility.Api

Or, add the package to your .csproj file:

<PackageReference Include="Ethik.Utility.Api" Version="1.0.0" />

Components

ApiError Class

Represents an API error with detailed information for error handling and reporting.

Properties
  • ErrorCode: A unique code identifying the error (default: "Unknown").
  • ErrorMessage: A descriptive message about the error.
  • ErrorDescription: A detailed description of the error.
  • ErrorSolution: A suggested solution for resolving the error.
  • Field: The name of the field associated with the error (if applicable).
  • Exception: Detailed information about the exception that caused the error.
  • ExceptionObj: The exception object used to populate the Exception property.
Example Usage
var apiError = new ApiError
{
    ErrorCode = "invalid_request",
    ErrorMessage = "The request parameters are invalid.",
    Field = "username",
    ExceptionObj = new Exception("Stack trace details")
};

Console.WriteLine(apiError.ToString());

ApiExceptionDetails Class

Represents detailed information about an exception.

Properties
  • Type: The type of the exception.
  • Message: The message associated with the exception.
  • StackTrace: The stack trace of the exception.
  • InnerException: The details of the inner exception, if any.

ApiErrorConfigService Internal class

Example Usage

// Program.cs
builder.Services.AddErrorConfig("MyApiErrors.json");
// MyApiErrors.json
{
  "Errors": {
    "Error1": {
      "ErrorCode": "FirstError",
      "ErrorMessage": "This is first error",
      "ErrorDescription": "First error description",
      "ErrorSolution": "Solution is nothing"
    },
    "Error2": {
      "ErrorCode": "SecondError",
      "ErrorMessage": "This is second error",
      "ErrorDescription": "Second error description",
      "ErrorSolution": "Solution is nothing"
    }
  }
}

GlobalExceptionHandler internal class

Example Usage

// Program.cs

builder.Services.AddGlobalExceptionHandler();

...

var app = builder.Build();

...

app.UseExceptionHandler();

app.Run();

ApiResponse<T> Class

A generic class to represent API responses with success or failure status.

Properties
  • Status: The status of the response (Success or Failure).
  • Message: A message describing the result of the operation.
  • StatusCode: HTTP status code for the response.
  • Data: The data returned by the operation (optional).
  • Errors: List of errors related to the operation (optional).
Methods
  • Success(T data, int statusCode = 200, string message = "Request was successful."): Creates a successful response.
  • Failure(string message, int statusCode, List<ApiError>? errors = null): Creates a failure response with optional errors.
  • Failure(string errorKey, string message, int statusCode = 500): Creates a failure response using an error key (ApiErrorCacheService needs to be added).
Example Usage
// Controller.cs
[HttpGet]
public async Task<IActionResult> ()
{
    var response = ApiResponse<int>.Success(
        32, 
        StatusCodes.Status200Ok,
        "User Age Fetched Successfully");
    return new ObjectResult(response) { StatusCode = response.StatusCode };

}
// Controller.cs
/* Assuming service is already added in Program.cs */
[HttpGet]
public async Task<IActionResult> ()
{
    var response = ApiResponse<int>.Failure(
        "Error2", 
        "Cannot process request, try again later", 
        StatusCodes.Status500InternalServerError);
    return new ObjectResult(response) { StatusCode = response.StatusCode };

}

ServiceCollectionExtensions Class

Provides extension methods for configuring services in the IServiceCollection.

Methods
  • AddErrorConfig(IServiceCollection services, string jsonFilePath):

    • Description: Adds and initializes the ApiErrorConfigService to the service collection using a JSON file for error caching.
    • Parameters:
      • services: The IServiceCollection to add the service to.
      • jsonFilePath: The file path to the JSON file used for error caching.
    • Returns: The updated IServiceCollection.
    • Example Usage:
      // In Startup.cs or Program.cs
      services.AddErrorConfig("path/to/error-cache.json");
      
  • AddGlobalExceptionHandler(IServiceCollection services):

    • Description: Adds global exception handling and ProblemDetails services to the service collection.
    • Parameters:
      • services: The IServiceCollection to add the services to.
    • Returns: The updated IServiceCollection.
    • Example Usage:
      // In Startup.cs or Program.cs
      services.AddGlobalExceptionHandler();
      
  • AddSwaggerGenWithAuth(IServiceCollection services):

    • Description: Adds Swagger with JWT bearer token authentication options enabled.
    • Parameters:
      • services: The IServiceCollection to add the services to.
    • Returns: The updated IServiceCollection.
    • Example Usage:
      // In Startup.cs or Program.cs
      services.AddSwaggerGenWithAuth();
      
Example Usage
// Program.cs or Startup.cs
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add and configure services
        services.AddErrorConfig("path/to/error-cache.json");
        services.AddJwtHelper(Configuration);
        services.AddGlobalExceptionHandler();
        services.AddSwaggerGenWithAuth();
    }

    // Other methods...
}

TODO

Need to add doc for these

ApiValidationException, ApiValidationFailure, Usages of validation exception in global exp handler, http client extensions, network utility

Add/update tests

Product Compatible and additional computed target framework versions.
.NET 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. 
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.0.2 149 4/26/2025
1.0.1 176 10/11/2024
1.0.0 166 9/30/2024