9. Understanding Response Types and Content Negotiation in Minimal APIs
Introduction: In Minimal APIs, specifying response types and content negotiation is crucial for defining the behavior of your endpoints. Let's explore how to use Produces
and Accepts
attributes effectively to document and enforce the expected behavior of your API endpoints.
Scenario 1: Returning a Collection of Coupons
csharpCopy codeapp.MapGet("/api/coupons", () =>
{
var coupons = GetCouponsFromDatabase(); // Example method to fetch coupons
return Results.Ok(coupons);
}).Produces<IEnumerable<Coupon>>(200).WithName("GetCoupons");
In this scenario, we define an endpoint that returns a collection of coupons. The Produces
attribute specifies that the endpoint produces a response of type IEnumerable<Coupon>
with a status code of 200 (OK) and names it "GetCoupons".
Scenario 2: Returning a Single Coupon
csharpCopy codeapp.MapGet("/api/coupon/{id}", (int id) =>
{
var coupon = GetCouponById(id); // Example method to fetch a coupon by ID
return coupon != null ? Results.Ok(coupon) : Results.NotFound();
}).Produces<Coupon>(200).WithName("GetCoupon");
Here, we define an endpoint that returns a single coupon based on the provided ID. The Produces<Coupon>(200)
attribute specifies that the endpoint produces a response of type Coupon
with a status code of 200 (OK) and names it "GetCoupon".
Scenario 3: Creating a New Coupon
csharpCopy codeapp.MapPost("/api/coupon", ([FromBody] Coupon coupon) =>
{
if (IsValidCoupon(coupon))
{
// Example method to create a new coupon in the database
CreateCoupon(coupon);
return Results.Created($"/api/coupon/{coupon.Id}", coupon);
}
else
{
return Results.BadRequest();
}
}).Accepts<Coupon>("application/json").Produces<Coupon>(201).Produces(400).WithName("CreateCoupon");
In this scenario, we define an endpoint for creating a new coupon. The Accepts
attribute specifies that the endpoint accepts requests with the content type of "application/json" containing data compatible with the Coupon
model. The Produces
attribute specifies that the endpoint produces a response of type Coupon
with a status code of 201 (Created) if the request is successful, and a response with a status code of 400 (Bad Request) if the request is not successful. This endpoint is named "CreateCoupon".
Conclusion: By using Produces
and Accepts
attributes in Minimal APIs, you can effectively document and enforce the expected behavior of your endpoints, ensuring clear communication between clients and servers. Understanding response types and content negotiation is essential for building robust and self-descriptive APIs.