RESTful APIs are the backbone of modern web and mobile applications. Whether you're building a simple backend for a front-end app or architecting a microservices system, knowing how to build robust APIs is essential. With the release of .NET 9, Microsoft has made backend development faster, more efficient, and developer-friendly.
This guide will walk you through the fundamentals and practical implementation of REST API development using .NET 9. By the end, you'll have a solid understanding of how to set up, structure, and secure a REST API using modern .NET practices.
Why Use .NET 9 for REST APIs?
.NET 9 builds upon the strong foundation of previous versions by improving runtime performance, simplifying minimal API development, and enhancing tooling. Here are a few reasons why .NET 9 is a top choice for backend API development:
- High performance and scalability
- Minimal API support for lightweight endpoints
- Integrated dependency injection
- Built-in support for Swagger/OpenAPI documentation
- First-class support for Entity Framework Core
Step-by-Step: Building a RESTful API with .NET 9
Let’s walk through creating a simple REST API for managing products.
1. Set Up the Project
Start by installing the latest .NET 9 SDK. Then, create a new Web API project using the .NET CLI.
dotnet new webapi -n ProductApi
cd ProductApi
The webapi
template sets up a ready-to-use REST API project with controllers, Swagger, and basic configuration.
2. Define the Model
Create a simple Product
model inside a Models
folder.
Models/Product.cs
namespace ProductApi.Models
{
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
public string Description { get; set; } = string.Empty;
}
}
3. Create the Data Context
Add a new class to manage your data context using Entity Framework Core.
Data/AppDbContext.cs
using Microsoft.EntityFrameworkCore;
using ProductApi.Models;
namespace ProductApi.Data
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) {}
public DbSet<Product> Products { get; set; }
}
}
Register this context in Program.cs
:
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("ProductsDb"));
Install the EF Core package if needed:
dotnet add package Microsoft.EntityFrameworkCore.InMemory
4. Create the Controller
Add a controller to handle the product-related HTTP requests.
Controllers/ProductsController.cs
using Microsoft.AspNetCore.Mvc;
using ProductApi.Data;
using ProductApi.Models;
namespace ProductApi.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private readonly AppDbContext _context;
public ProductsController(AppDbContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<IEnumerable<Product>> GetAll()
{
return Ok(_context.Products.ToList());
}
[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
var product = _context.Products.Find(id);
if (product == null) return NotFound();
return Ok(product);
}
[HttpPost]
public ActionResult<Product> Create(Product product)
{
_context.Products.Add(product);
_context.SaveChanges();
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
[HttpPut("{id}")]
public IActionResult Update(int id, Product updatedProduct)
{
var product = _context.Products.Find(id);
if (product == null) return NotFound();
product.Name = updatedProduct.Name;
product.Price = updatedProduct.Price;
product.Description = updatedProduct.Description;
_context.SaveChanges();
return NoContent();
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
var product = _context.Products.Find(id);
if (product == null) return NotFound();
_context.Products.Remove(product);
_context.SaveChanges();
return NoContent();
}
}
}
5. Configure Swagger and Middleware
By default, Swagger is already enabled in the Program.cs
file. If not, make sure you include:
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
In the middleware pipeline:
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
Test the API
Run the application:
dotnet run
Visit https://localhost:5001/swagger
(or your configured port) to explore your API using Swagger UI.
Best Practices for Building REST APIs
- Use proper HTTP status codes (200 OK, 201 Created, 404 Not Found, etc.)
-
Keep routes RESTful using nouns (e.g.,
/api/products
) - Implement authentication and authorization using JWT or OAuth
- Use DTOs (Data Transfer Objects) to prevent over-posting
- Add input validation using model annotations or FluentValidation
- Write unit and integration tests to ensure your API’s stability
Conclusion
.NET 9 makes API development smoother, faster, and more efficient. Whether you are creating simple endpoints or architecting a large backend, you can build powerful RESTful APIs with minimal setup and maximum performance.
If you'd like to learn more and access full .NET API projects with source code, check out my resources below:
📚 Get my development ebooks and resources:
https://codewithdhanian.gumroad.com
🐦 Follow me on X (formerly Twitter):
@e_opore
Top comments (0)