DotNetApiContracts 1.0.0
dotnet add package DotNetApiContracts --version 1.0.0
NuGet\Install-Package DotNetApiContracts -Version 1.0.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="DotNetApiContracts" Version="1.0.0" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DotNetApiContracts" Version="1.0.0" />
<PackageReference Include="DotNetApiContracts" />
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 DotNetApiContracts --version 1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: DotNetApiContracts, 1.0.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 DotNetApiContracts@1.0.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=DotNetApiContracts&version=1.0.0
#tool nuget:?package=DotNetApiContracts&version=1.0.0
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
DotNetApiContracts
API design patterns and contracts for consistent API responses, pagination standards, versioning, DTO mapping, and idempotency.
Problems Solved
- Inconsistent API responses: Different endpoints return different response formats
- Pagination standards missing: Each endpoint implements pagination differently
- API versioning confusion: Unclear how to version APIs
- Breaking client contracts: Changes break existing clients
- Swagger docs out of sync: API documentation doesn't match implementation
- DTO mapping boilerplate: Repetitive mapping code between entities and DTOs
- Idempotency missing: Duplicate requests processed multiple times
Installation
dotnet add package DotNetApiContracts
Quick Start
1. Consistent API Responses
Problem: Different endpoints return different response formats, making client integration difficult.
using DotNetApiContracts;
// ❌ BAD: Inconsistent responses
[HttpGet]
public IActionResult GetUsers()
{
return Ok(users); // Returns array directly
}
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
return Ok(new { data = user }); // Different format
}
// ✅ GOOD: Consistent response format
[HttpGet]
public IActionResult GetUsers()
{
var users = _userService.GetUsers();
return ApiResponse<IEnumerable<User>>.Ok(users).ToActionResult();
}
[HttpGet("{id}")]
public IActionResult GetUser(int id)
{
var user = _userService.GetUser(id);
return ApiResponse<User>.Ok(user).ToActionResult();
}
[HttpPost]
public IActionResult CreateUser(CreateUserRequest request)
{
var user = _userService.CreateUser(request);
return ApiResponse<User>.Ok(user, "User created successfully").ToActionResult();
}
2. Standardized Pagination
Problem: Each endpoint implements pagination differently.
// ✅ GOOD: Consistent pagination format
[HttpGet]
public async Task<ActionResult<PagedApiResponse<User>>> GetUsers(
int page = 1,
int pageSize = 20)
{
var result = await _userService.GetUsersPagedAsync(page, pageSize);
return PagedApiResponse<User>.Ok(
result.Items,
result.PageNumber,
result.PageSize,
result.TotalCount
).ToActionResult();
}
// Response format:
{
"success": true,
"data": [...],
"pagination": {
"pageNumber": 1,
"pageSize": 20,
"totalCount": 100,
"totalPages": 5,
"hasNextPage": true,
"hasPreviousPage": false
}
}
3. Idempotent Requests
Problem: Duplicate requests (network retries) process the same operation multiple times.
// ✅ GOOD: Add idempotency middleware
app.UseIdempotency(options =>
{
options.HeaderName = "Idempotency-Key";
options.CacheExpiration = TimeSpan.FromHours(24);
});
// Client sends request with idempotency key
POST /api/orders
Headers:
Idempotency-Key: abc123-def456-ghi789
// First request processes normally
// Duplicate requests return cached response
4. Error Responses
Problem: Error responses inconsistent with success responses.
// ✅ GOOD: Consistent error format
[HttpPost]
public async Task<IActionResult> CreateOrder(CreateOrderRequest request)
{
try
{
var order = await _orderService.CreateOrderAsync(request);
return ApiResponse<Order>.Ok(order).ToActionResult();
}
catch (ValidationException ex)
{
return ApiResponse<Order>.Error(
ex.Message,
new Dictionary<string, object> { ["errors"] = ex.Errors }
).ToActionResult();
}
}
Real-World Example
[ApiController]
[Route("api/v1/[controller]")]
public class OrdersController : ControllerBase
{
private readonly IOrderService _orderService;
// GET /api/v1/orders?page=1&pageSize=20
[HttpGet]
public async Task<ActionResult<PagedApiResponse<Order>>> GetOrders(
int page = 1,
int pageSize = 20)
{
var result = await _orderService.GetOrdersPagedAsync(page, pageSize);
return PagedApiResponse<Order>.Ok(
result.Items,
result.PageNumber,
result.PageSize,
result.TotalCount
).ToActionResult();
}
// GET /api/v1/orders/123
[HttpGet("{id}")]
public async Task<ActionResult<ApiResponse<Order>>> GetOrder(int id)
{
var order = await _orderService.GetOrderAsync(id);
if (order == null)
{
return ApiResponse<Order>.Error("Order not found").ToActionResult();
}
return ApiResponse<Order>.Ok(order).ToActionResult();
}
// POST /api/v1/orders
// Headers: Idempotency-Key: abc123
[HttpPost]
public async Task<ActionResult<ApiResponse<Order>>> CreateOrder(
CreateOrderRequest request)
{
try
{
var order = await _orderService.CreateOrderAsync(request);
return ApiResponse<Order>.Ok(order, "Order created successfully").ToActionResult();
}
catch (ValidationException ex)
{
return ApiResponse<Order>.Error(ex.Message).ToActionResult();
}
}
// PUT /api/v1/orders/123
[HttpPut("{id}")]
public async Task<ActionResult<ApiResponse<Order>>> UpdateOrder(
int id,
UpdateOrderRequest request)
{
try
{
var order = await _orderService.UpdateOrderAsync(id, request);
return ApiResponse<Order>.Ok(order, "Order updated successfully").ToActionResult();
}
catch (NotFoundException)
{
return ApiResponse<Order>.Error("Order not found").ToActionResult();
}
}
}
// Program.cs - Configure idempotency
var app = builder.Build();
// Add idempotency middleware (before other middleware)
app.UseIdempotency(options =>
{
options.HeaderName = "Idempotency-Key";
options.QueryParameterName = "idempotencyKey"; // Fallback to query param
options.CacheExpiration = TimeSpan.FromHours(24);
});
app.MapControllers();
app.Run();
Response Format Examples
Success Response
{
"success": true,
"data": {
"id": 123,
"total": 100.00
},
"message": "Order created successfully"
}
Paginated Response
{
"success": true,
"data": [
{ "id": 1, "total": 100.00 },
{ "id": 2, "total": 200.00 }
],
"pagination": {
"pageNumber": 1,
"pageSize": 20,
"totalCount": 100,
"totalPages": 5,
"hasNextPage": true,
"hasPreviousPage": false
}
}
Error Response
{
"success": false,
"message": "Validation failed",
"metadata": {
"errors": {
"email": ["Invalid email format"]
}
}
}
Idempotency Usage
Client Side
// Generate idempotency key (store for retries)
var idempotencyKey = Guid.NewGuid().ToString();
// First request
var response = await httpClient.PostAsJsonAsync(
"/api/orders",
request,
new Dictionary<string, string>
{
["Idempotency-Key"] = idempotencyKey
}
);
// If request fails, retry with same key
// Server returns cached response instead of processing again
Best Practices
- Use
ApiResponse<T>for all API responses (success and error) - Use
PagedApiResponse<T>for paginated endpoints - Enable idempotency for POST/PUT/PATCH/DELETE operations
- Include meaningful messages in success and error responses
- Use consistent error format across all endpoints
- Document idempotency in API documentation
- Set appropriate cache expiration for idempotency (24 hours typical)
API Reference
ApiResponse<T>- Standard API response wrapperPagedApiResponse<T>- Paginated API responsePaginationInfo- Pagination metadataIdempotencyMiddleware- Middleware for idempotent requestsUseIdempotency()- Extension method to enable idempotencyToActionResult()- Convert response to IActionResult
| Product | Versions 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.
-
net8.0
- Microsoft.Extensions.Caching.Memory (>= 8.0.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 8.0.0)
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.0 | 156 | 12/29/2025 |
Initial release. See README for details.