Modern applications rarely work in isolation. A website might need to communicate with a mobile application, retrieve information from a database, or share data with another service. REST APIs make this communication possible through a standard set of HTTP methods.
ASP.NET Core provides a straightforward way to build these APIs using C#. It includes routing, dependency injection, request validation, middleware, and other features that help developers build maintainable applications.
In this tutorial, we'll create a simple Coupon Management API. It will allow clients to add coupons, retrieve available offers, update existing records, and delete expired or unwanted entries.
The example is useful for understanding how an application can manage structured information, whether it's an internal business tool, an e-commerce platform, or a discount service such as RabattDigga.
Let's build it step by step.
1. Create an ASP.NET Core Web API Project
First, make sure you have the .NET SDK installed.
Open your terminal and execute:
dotnet new webapi --use-controllers -n CouponManagementApi
Move into the project directory:
cd CouponManagementApi
Open the project in Visual Studio or Visual Studio Code.
The project provides the basic structure needed to start developing an API.
2. Install Entity Framework Core
We'll use Entity Framework Core to communicate with SQL Server.
Install the required packages:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Entity Framework Core allows developers to work with database records through C# objects instead of writing SQL queries for every operation.
3. Create the Coupon Model
Now create a folder called Models and add a class named Coupon.cs.
This class represents the coupon information stored in our database.
using System.ComponentModel.DataAnnotations;
namespace CouponManagementApi.Models
{
public class Coupon
{
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Title { get; set; } = string.Empty;
[Required]
[StringLength(50)]
public string Code { get; set; } = string.Empty;
[Range(1, 100)]
public decimal DiscountPercentage { get; set; }
public DateTime ExpiryDate { get; set; }
public bool IsActive { get; set; } = true;
}
}
Here is what each property represents:
Id: Unique identifier for each coupon.
Title: Name or description of the offer.
Code: Promotional code customers can use.
DiscountPercentage: Discount value.
ExpiryDate: Date when the coupon expires.
IsActive: Indicates whether the coupon is active.
The validation attributes help prevent incomplete or invalid information from entering the application.
4. Configure the Database Context
Create a folder named Data and add ApplicationDbContext.cs.
using Microsoft.EntityFrameworkCore;
using CouponManagementApi.Models;
namespace CouponManagementApi.Data
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(
DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Coupon> Coupons { get; set; }
}
}
The DbContext represents the database session. The Coupons property allows us to perform database operations on coupon records.
5. Configure SQL Server Connection
Open appsettings.json and add your SQL Server connection string.
{
"ConnectionStrings": {
"DefaultConnection": "Server=YOUR_SERVER;Database=CouponManagementDb;Trusted_Connection=True;TrustServerCertificate=True"
}
}
Replace YOUR_SERVER with your actual SQL Server instance.
Now open Program.cs and register the database context:
using CouponManagementApi.Data;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Dependency injection handles the creation and lifetime of the database context. This keeps database configuration separate from the controller logic.
6. Create the Coupon Controller
Now comes the main part of our application.
Create a Controllers folder if it doesn't already exist, and add CouponsController.cs.
using CouponManagementApi.Data;
using CouponManagementApi.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace CouponManagementApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class CouponsController : ControllerBase
{
private readonly ApplicationDbContext _context;
public CouponsController(ApplicationDbContext context)
{
_context = context;
}
// GET: api/coupons
[HttpGet]
public async Task<IActionResult> GetCoupons()
{
var coupons = await _context.Coupons
.AsNoTracking()
.ToListAsync();
return Ok(coupons);
}
// GET: api/coupons/5
[HttpGet("{id}")]
public async Task<IActionResult> GetCoupon(int id)
{
var coupon = await _context.Coupons.FindAsync(id);
if (coupon == null)
return NotFound();
return Ok(coupon);
}
// POST: api/coupons
[HttpPost]
public async Task<IActionResult> CreateCoupon(Coupon coupon)
{
_context.Coupons.Add(coupon);
await _context.SaveChangesAsync();
return CreatedAtAction(
nameof(GetCoupon),
new { id = coupon.Id },
coupon);
}
// PUT: api/coupons/5
[HttpPut("{id}")]
public async Task<IActionResult> UpdateCoupon(
int id, Coupon updatedCoupon)
{
var coupon = await _context.Coupons.FindAsync(id);
if (coupon == null)
return NotFound();
coupon.Title = updatedCoupon.Title;
coupon.Code = updatedCoupon.Code;
coupon.DiscountPercentage =
updatedCoupon.DiscountPercentage;
coupon.ExpiryDate = updatedCoupon.ExpiryDate;
coupon.IsActive = updatedCoupon.IsActive;
await _context.SaveChangesAsync();
return NoContent();
}
// DELETE: api/coupons/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteCoupon(int id)
{
var coupon = await _context.Coupons.FindAsync(id);
if (coupon == null)
return NotFound();
_context.Coupons.Remove(coupon);
await _context.SaveChangesAsync();
return NoContent();
}
}
}
Let's understand what we have implemented.
GET retrieves all coupons.
GET/{id} retrieves a specific coupon.
POST creates a new coupon.
PUT/{id} updates an existing coupon.
DELETE/{id} removes a coupon.
Notice that we are using asynchronous methods such as ToListAsync() and SaveChangesAsync(). These are particularly useful for database operations because they allow the application to handle other requests while waiting for I/O operations.
7. Create the Database Using Migrations
Our model and database context are ready. Now we need to create the actual database tables.
Run these commands:
dotnet ef migrations add InitialCreate
Then apply the migration:
dotnet ef database update
Entity Framework Core generates the database schema based on the model and applies it to SQL Server.
You should now have a database named CouponManagementDb with a Coupons table.
8. Test the REST API
Run the application:
dotnet run
Open the Swagger interface using the HTTPS URL displayed in your terminal, followed by /swagger.
You can test each endpoint directly from the browser.
For example, to create a coupon, send a POST request with this JSON:
{
"title": "Summer Shopping Offer",
"code": "SUMMER20",
"discountPercentage": 20,
"expiryDate": "2027-06-30T23:59:59",
"isActive": true
}
The API should return a 201 Created response when the record is successfully added.
You can then use:
GET /api/coupons
to retrieve all coupon records.
Similarly, try updating a coupon using PUT or removing it using DELETE.
9. Important Improvements for a Production API
The implementation above provides a working starting point, but a production application needs additional considerations.
Use DTOs
Avoid exposing database entities directly to API clients. Data Transfer Objects (DTOs) allow you to control which properties clients can submit or receive.
Add Authentication and Authorization
Not every user should be able to create, update, or delete records. ASP.NET Core supports authentication and authorization mechanisms to protect sensitive endpoints.
Handle Errors Properly
Unexpected database failures and invalid requests should return meaningful HTTP responses. Centralized exception handling can make error management easier.
Implement Pagination
Returning thousands of records in one response can affect performance. Pagination allows clients to request smaller groups of records.
Validate Business Rules
A coupon should not be considered available simply because its IsActive property is true. Its expiry date, usage restrictions, and other business rules should also be checked.
Protect Sensitive Configuration
Database credentials and other secrets should not be stored directly in publicly accessible configuration files. Use appropriate secret-management solutions.
Conclusion
Building a REST API with ASP.NET Core and C# becomes much easier when the application is divided into clear components. Controllers handle incoming requests, Entity Framework Core manages database communication, and dependency injection connects the different parts.
In this example, we created a basic Coupon Management API with complete CRUD functionality using SQL Server.
The same approach can be extended to inventory systems, customer management platforms, booking applications, and e-commerce solutions.
The important thing is not just getting an API working. It's designing it so that other applications can communicate with it reliably, data remains consistent, and future changes don't turn into unnecessary development work.
Once these fundamentals are clear, developers can move toward more advanced topics such as repository patterns, caching, API versioning, background services, and automated testing.
Join the conversation! Your thoughts help the community grow.