DEV Community

CodeWithDhanian
CodeWithDhanian

Posted on

Become a Pro at Building RESTful APIs Using .NET 9

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
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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; }
    }
}
Enter fullscreen mode Exit fullscreen mode

Register this context in Program.cs:

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseInMemoryDatabase("ProductsDb"));
Enter fullscreen mode Exit fullscreen mode

Install the EF Core package if needed:

dotnet add package Microsoft.EntityFrameworkCore.InMemory
Enter fullscreen mode Exit fullscreen mode

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();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

In the middleware pipeline:

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
Enter fullscreen mode Exit fullscreen mode

Test the API

Run the application:

dotnet run
Enter fullscreen mode Exit fullscreen mode

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

Tiugo image

Fast, Lean, and Fully Extensible

CKEditor 5 is built for developers who value flexibility and speed. Pick the features that matter, drop the ones that don’t and enjoy a high-performance WYSIWYG that fits into your workflow

Start now

Top comments (0)

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping

👋 Kindness is contagious

Explore this insightful write-up, celebrated by our thriving DEV Community. Developers everywhere are invited to contribute and elevate our shared expertise.

A simple "thank you" can brighten someone’s day—leave your appreciation in the comments!

On DEV, knowledge-sharing fuels our progress and strengthens our community ties. Found this useful? A quick thank you to the author makes all the difference.

Okay