6. Implementing a "Get Individual Coupon" Endpoint in ASP.NET Core Minimal API

ยท

2 min read

In this post, we'll walk through the implementation of an API endpoint to retrieve individual coupons in an ASP.NET Core application. We'll use the app.MapGet method to define a route that accepts an integer parameter representing the coupon ID and returns the corresponding coupon object.

Setting Up the Project First, make sure you have an ASP.NET Core project set up. You can create a new project using the dotnet new command or use an existing project.

Define Coupon Model Let's define a simple model for our coupon:

public class Coupon
{
    public int Id { get; set; }
    public string Code { get; set; }
    // Add other properties as needed
}

Coupon Store For demonstration purposes, we'll use a static list to store coupons. In a real-world scenario, you would replace this with a database or some other data storage mechanism.

public static class CouponStore
{
    public static List<Coupon> couponList = new List<Coupon>
    {
        new Coupon { Id = 1, Code = "SAVE10" },
        new Coupon { Id = 2, Code = "DISCOUNT20" }
        // Add more coupons as needed
    };
}

Implement the Endpoint Now, let's implement the "Get Individual Coupon" endpoint:

app.MapGet("/api/coupon/{id:int}", (int id) => {
    return Results.Ok(CouponStore.couponList.FirstOrDefault(u => u.Id == id));
});

In this code snippet:

  • We use the app.MapGet method to define a GET endpoint.

  • The {id:int} part of the route specifies that the id parameter must be an integer.

  • We retrieve the coupon from the CouponStore.couponList based on the provided ID.

  • If a matching coupon is found, it's returned as the response using Results.Ok. Otherwise, a 404 Not Found response is returned automatically.

Testing the Endpoint You can now test the endpoint using tools like Postman or cURL. Send a GET request to /api/coupon/{id} (replace {id} with the desired coupon ID) to retrieve the individual coupon.

Conclusion In this tutorial, we learned how to implement a simple "Get Individual Coupon" endpoint in an ASP.NET Core application. You can extend this example by adding authentication, pagination, or integrating with a database to store coupons persistently.

Happy coding!

ย