Modern applications often need to share data between websites, mobile apps, and backend services. REST APIs make this communication possible by providing structured endpoints that applications can use to exchange data.
ASP.NET Core provides a flexible framework for building REST APIs using C#. It includes features for handling HTTP requests, routing, dependency injection, authentication, and application configuration.
In this tutorial, we will build a simple Coupon Management API using ASP.NET Core. The API will allow clients to retrieve, create, and delete coupons.
By the end, you will understand how to create an ASP.NET Core Web API project, define a model, implement API controllers, configure the application, and test endpoints using Swagger.
1. Create an ASP.NET Core Web API Project
Before starting, ensure that the .NET SDK is installed on your machine.
Open a terminal and run the following command to create a new Web API project:
dotnet new webapi --use-controllers -n CouponManagementAPIMove into the project directory:
cd CouponManagementAPIOpen the project in Visual Studio or Visual Studio Code.
The project contains the basic configuration and files required to start building an ASP.NET Core Web API.
2. Create the Coupon Model
An API needs a data model to represent the information it manages.
Create a folder named Models in the project and add a new file called Coupon.cs.
Add the following code:
namespace CouponManagementAPI.Models
{
public class Coupon
{
public int Id { get; set; }
public string Code { get; set; } = string.Empty;
public decimal DiscountPercentage { get; set; }
public DateTime ExpiryDate { get; set; }
public bool IsActive { get; set; }
}
}The Coupon class represents a discount coupon in our application.
Each property has a specific purpose:
Id: A unique identifier for each coupon.
Code: The coupon code that customers can use.
DiscountPercentage: The discount percentage offered by the coupon.
ExpiryDate: The date when the coupon expires.
IsActive: Indicates whether the coupon is currently active.
For example, a coupon with the code SAVE20 could provide a 20% discount until its expiry date.
3. Create the Coupons Controller
Controllers handle incoming HTTP requests and return appropriate responses to clients.
Create a folder named Controllers and add a file called CouponsController.cs.
Add the following implementation:
using Microsoft.AspNetCore.Mvc;
using CouponManagementAPI.Models;
namespace CouponManagementAPI.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class CouponsController : ControllerBase
{
private static readonly List<Coupon> coupons = new()
{
new Coupon
{
Id = 1,
Code = "SAVE20",
DiscountPercentage = 20,
ExpiryDate = DateTime.UtcNow.AddDays(30),
IsActive = true
}
};
[HttpGet]
public IActionResult GetCoupons()
{
return Ok(coupons);
}
[HttpGet("{id}")]
public IActionResult GetCoupon(int id)
{
var coupon = coupons.FirstOrDefault(c => c.Id == id);
if (coupon == null)
return NotFound();
return Ok(coupon);
}
[HttpPost]
public IActionResult CreateCoupon(Coupon coupon)
{
coupon.Id = coupons.Count + 1;
coupons.Add(coupon);
return CreatedAtAction(
nameof(GetCoupon),
new { id = coupon.Id },
coupon
);
}
[HttpDelete("{id}")]
public IActionResult DeleteCoupon(int id)
{
var coupon = coupons.FirstOrDefault(c => c.Id == id);
if (coupon == null)
return NotFound();
coupons.Remove(coupon);
return NoContent();
}
}
}Let's understand the main parts of this controller.
Controller Attributes
The [ApiController] attribute enables API-specific behavior, including automatic request validation and improved parameter binding.
The [Route("api/[controller]")] attribute defines the base route for the controller.
Since our controller is named CouponsController, the base endpoint becomes:
/api/couponsGET - Retrieve All Coupons
The GetCoupons method returns all available coupons.
[HttpGet]
public IActionResult GetCoupons()
{
return Ok(coupons);
}The Ok() method returns an HTTP 200 response along with the coupon data.
GET - Retrieve a Coupon by ID
The GetCoupon method searches for a coupon using its ID.
[HttpGet("{id}")]
public IActionResult GetCoupon(int id)
{
var coupon = coupons.FirstOrDefault(c => c.Id == id);
if (coupon == null)
return NotFound();
return Ok(coupon);
}If the coupon exists, the API returns it. Otherwise, it returns an HTTP 404 Not Found response.
POST - Create a New Coupon
The CreateCoupon method accepts coupon information from the request body.
[HttpPost]
public IActionResult CreateCoupon(Coupon coupon)
{
coupon.Id = coupons.Count + 1;
coupons.Add(coupon);
return CreatedAtAction(
nameof(GetCoupon),
new { id = coupon.Id },
coupon
);
}
Join the conversation! Your thoughts help the community grow.