ApiUtilities.Common 1.1.1

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

ApiUtilities NuGet Package

Overview

The ApiUtilities package provides a simplified way to interact with HTTP APIs in .NET applications. It encapsulates common HTTP methods (GET, POST, PUT, DELETE) and manages configuration, authentication, and error handling, making it easy to perform API requests.

Installation

To install the package, use the NuGet Package Manager Console:

Install-Package ApiUtilities

Usage

Configuration Interface

First, implement the IBaseConfiguration interface to provide the necessary configuration for your HTTP client.

public class ApiConfiguration : IBaseConfiguration
{
    public string BaseUrl { get; set; }
    public string AuthToken { get; set; }
    public IDictionary<string, string> Headers { get; set; }
    public int TimeoutSeconds { get; set; } = 30; // Default timeout
}

Service Registration

Register the necessary services in your dependency injection container.

public class ServiceRegistration : BaseServiceRegistration
{
    public ServiceRegistration(IServiceCollection serviceCollection) : base(serviceCollection)
    {
        services.AddSingleton<IBaseConfiguration>(configuration);
    }

    protected override void RegisterOverride()
    {
        // Add custom service registrations here if needed
    }
}

---

var services = new ServiceCollection();
var configuration = new ApiConfiguration
{
    BaseUrl = "https://api.example.com",
    AuthToken = "your_token",
    Headers = new Dictionary<string, string>
    {
        { "Custom-Header", "value" }
    }
};

services.AddSingleton<IBaseConfiguration>(configuration);
new ServiceRegistration(services);
var serviceProvider = services.BuildServiceProvider();

Using the BaseService

public class MyService
{
    private readonly BaseService _baseService;

    public MyService(BaseService baseService)
    {
        _baseService = baseService;
    }

    public async Task DoSomethingAsync()
    {
        var response = await _baseService.Get<MyResponse>("endpoint");
        if (response.Error == null)
        {
            // Handle successful response
        }
        else
        {
            // Handle error
        }
    }
}

Models

Define your response models inheriting from BaseResponse.

public class MyResponse : BaseResponse
{
    public int Id { get; set; }
    public string Name { get; set; }
}

API Methods

Get Request

var response = await _baseService.Get<MyResponse>("endpoint");

Post Request

var data = new { Property1 = "value", Property2 = "value" };
var response = await _baseService.Post<MyResponse>("endpoint", data);

Put Request

var data = new { Property1 = "value", Property2 = "value" };
var response = await _baseService.Put<MyResponse>("endpoint", data);

Delete Request

var response = await _baseService.Delete<MyResponse>("endpoint");

Error Handling

If the request fails and requireSuccess is set to true, an HttpRequestException will be thrown. If requireSuccess is set to false, the error will be set in the ResponseContainer.

Cancellation and Timeout

All methods accept a CancellationToken which can be used to cancel the request. The default timeout for requests can be configured via the TimeoutSeconds property in IBaseConfiguration.

Unit Testing

Mocking HTTP requests and responses can be achieved using the provided IHttpClientService. Here is an example using Moq:

public class BaseServiceTests
{
    [Fact]
    public async Task Get_SuccessfulRequest_ReturnsResponseContainerWithData()
    {
        // Arrange
        var httpClientServiceMock = new Mock<IHttpClientService>();
        var config = new ApiConfiguration { BaseUrl = "https://example.com", AuthToken = "dummy_token", TimeoutSeconds = 30 };

        var responseData = new MyResponse { Id = 1, Name = "Test" };
        var json = JsonConvert.SerializeObject(responseData);

        httpClientServiceMock.Setup(c => c.GetAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
            .ReturnsAsync(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content = new StringContent(json, Encoding.UTF8, "application/json")
            });

        var baseService = new BaseService(httpClientServiceMock.Object, config);

        // Act
        var responseContainer = await baseService.Get<MyResponse>("test");

        // Assert
        Assert.NotNull(responseContainer);
        Assert.Null(responseContainer.Error);
        Assert.NotNull(responseContainer.Data);
        Assert.Equal(responseData.Id, responseContainer.Data.Id);
        Assert.Equal(responseData.Name, responseContainer.Data.Name);
    }
}

Conclusion

ApiUtilities simplifies HTTP API interactions in .NET applications by providing a configurable and extendable base service. By following the steps outlined in this documentation, you can quickly integrate and use the package in your projects.

Contributing

Contributions are welcome! Please follow the contribution guidelines when submitting pull requests.

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  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 was computed.  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 was computed.  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.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on ApiUtilities.Common:

Package Downloads
RickNMorty.Common

A Api Wrapper For The Rick And Morty Api

PoliceAPI.Common

Package Description

ApiAlerts.Common

Package Description

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.1 174 7/14/2024 1.1.1 is deprecated because it is no longer maintained.
1.1.0 121 7/14/2024
1.0.9 225 3/13/2024
1.0.8 126 3/13/2024
1.0.7 134 3/13/2024
1.0.6 166 3/4/2024
1.0.5 178 2/1/2024
1.0.4 271 1/17/2024
1.0.3 274 1/1/2024
1.0.2 245 12/23/2023
1.0.1 169 12/23/2023
1.0.0 150 12/23/2023