11. Adding DTOs and Creating a Coupon API in ASP.NET Core in MinimalAPI
In this tutorial, we'll create a simple API for managing coupons using ASP.NET Core. We will define Data Transfer Objects (DTOs) for creating and retrieving coupon data and set up an API endpoint to handle coupon creation.
Step 1: Define the DTO Classes
We start by defining two DTO classes: one for creating a new coupon (CouponCreateDTO
) and another for returning coupon data (CouponDTO
).
public class CouponCreateDTO
{
public string Name { get; set; }
public int Percent { get; set; }
public bool IsActive { get; set; }
}
public class CouponDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int Percent { get; set; }
public bool IsActive { get; set; }
public DateTime? Created { get; set; }
}
CouponCreateDTO
is used for incoming data when creating a new coupon.CouponDTO
is used for outgoing data when returning coupon details.
Step 2: Create the Coupon Entity
Next, define the Coupon
entity which represents a coupon in our system.
public class Coupon
{
public int Id { get; set; }
public string Name { get; set; }
public int Percent { get; set; }
public bool IsActive { get; set; }
public DateTime Created { get; set; } = DateTime.UtcNow;
}
Step 3: Create a Static Coupon Store
We'll use a static class to simulate an in-memory data store for our coupons.
public static class CouponStore
{
public static List<Coupon> couponList = new List<Coupon>();
}
Step 4: Set Up the API Endpoint
Now, set up our API endpoint using ASP.NET Core's minimal API approach.
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapPost("/api/coupon", ([FromBody] CouponCreateDTO couponCreateDTO) =>
{
// Validate the incoming data
if (string.IsNullOrEmpty(couponCreateDTO.Name))
{
return Results.BadRequest("Invalid Id or Coupon Name");
}
// Check if the coupon name already exists
if (CouponStore.couponList.Any(c => c.Name.Equals(couponCreateDTO.Name, StringComparison.OrdinalIgnoreCase)))
{
return Results.BadRequest("Coupon Name already Exists");
}
// Create a new coupon entity
var newCoupon = new Coupon
{
Name = couponCreateDTO.Name,
Percent = couponCreateDTO.Percent,
IsActive = couponCreateDTO.IsActive
};
// Assign a new ID to the coupon
newCoupon.Id = CouponStore.couponList.Any() ? CouponStore.couponList.Max(c => c.Id) + 1 : 1;
// Add the new coupon to the store
CouponStore.couponList.Add(newCoupon);
// Create a CouponDTO to return
var couponDTO = new CouponDTO
{
Id = newCoupon.Id,
Name = newCoupon.Name,
Percent = newCoupon.Percent,
IsActive = newCoupon.IsActive,
Created = newCoupon.Created
};
return Results.CreatedAtRoute("GetCoupon", new { id = newCoupon.Id }, couponDTO);
})
.WithName("CreateCoupon")
.Accepts<CouponCreateDTO>("application/json")
.Produces<CouponDTO>(201)
.Produces(400);
app.Run();
Explanation:
Endpoint Definition:
We define a POST endpoint at
/api/coupon
.The endpoint accepts a
CouponCreateDTO
object from the request body.
Validation:
We validate that the
Name
field is not empty.We check for the uniqueness of the coupon name.
Coupon Creation:
We create a new
Coupon
object and assign it a unique ID.We add the new coupon to our static store.
Response:
We create a
CouponDTO
object with the details of the new coupon.We return a 201 Created response with the
CouponDTO
.
Running the Application
To run the application, use the following commands:
dotnet build
dotnet run
You can test the API using a tool like Postman or cURL. Here's an example cURL command to create a new coupon:
curl -X POST "http://localhost:5000/api/coupon" -H "Content-Type: application/json" -d '{
"Name": "Discount2024",
"Percent": 20,
"IsActive": true
}'
Conclusion
In this tutorial, we've created a simple API for managing coupons using ASP.NET Core. We defined DTOs for data transfer, created a static store for in-memory data, and set up an endpoint for creating new coupons. This basic setup can be extended further to include more CRUD operations and validations as needed.
Happy coding!