ApiUtilities.Common
1.1.1
dotnet add package ApiUtilities.Common --version 1.1.1
NuGet\Install-Package ApiUtilities.Common -Version 1.1.1
<PackageReference Include="ApiUtilities.Common" Version="1.1.1" />
<PackageVersion Include="ApiUtilities.Common" Version="1.1.1" />
<PackageReference Include="ApiUtilities.Common" />
paket add ApiUtilities.Common --version 1.1.1
#r "nuget: ApiUtilities.Common, 1.1.1"
#:package ApiUtilities.Common@1.1.1
#addin nuget:?package=ApiUtilities.Common&version=1.1.1
#tool nuget:?package=ApiUtilities.Common&version=1.1.1
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 | Versions 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. |
-
.NETStandard 2.1
- Microsoft.Extensions.Http (>= 8.0.0)
- Newtonsoft.Json (>= 13.0.3)
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.