.NET Tutorials

Learn to build modern applications with .NET

Building a Web API with .NET 8

This tutorial guides you through creating a robust and efficient Web API using .NET 8. We'll cover essential concepts like routing, request handling, data persistence, and best practices for building scalable APIs.

Prerequisites:
  • .NET 8 SDK installed
  • A code editor (e.g., Visual Studio, VS Code)
  • Basic understanding of C# and RESTful principles

1. Setting Up Your Project

Let's start by creating a new ASP.NET Core Web API project. Open your terminal or command prompt and run the following command:

dotnet new webapi -o MyWeatherApi --no-https

This command creates a new directory named MyWeatherApi and initializes a Web API project within it. The --no-https flag simplifies initial setup by disabling HTTPS for local development.

2. Understanding the Project Structure

Navigate into the newly created project directory. You'll find a standard ASP.NET Core project structure:

3. Creating a Model

Define the data structure for your API. Let's create a simple WeatherForecast.cs model:

dotnet new class -n Models/WeatherForecast

Open Models/WeatherForecast.cs and add the following code:

namespace MyWeatherApi.Models;

public class WeatherForecast
{
    public DateOnly Date { get; set; }
    public int TemperatureC { get; set; }
    public string? Summary { get; set; }

    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

4. Creating a Controller

Now, let's create an API controller to handle requests. We'll create a WeatherForecastController.cs:

dotnet new controller -n WeatherForecastController -api -outdir Controllers

Replace the contents of Controllers/WeatherForecastController.cs with the following:

using Microsoft.AspNetCore.Mvc;
using MyWeatherApi.Models;

namespace MyWeatherApi.Controllers;

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }

    [HttpGet("{id}")]
    public ActionResult<WeatherForecast> GetById(int id)
    {
        if (id < 1 || id > 5)
        {
            return NotFound();
        }
        var forecast = new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(id)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        };
        return Ok(forecast);
    }
}

5. Running the API

Save all your changes and run the API from your project directory:

dotnet run

Your API will be running, typically at https://localhost:7041 (or http://localhost:5041 without HTTPS). You can test the endpoint by navigating to https://localhost:7041/weatherforecast in your browser.

Testing the API with cURL

curl https://localhost:7041/weatherforecast
Tip: For more complex APIs, consider using Dependency Injection for data access and services.

6. Adding Input Validation

Robust APIs require input validation. You can use data annotations for this purpose. Let's add validation to a hypothetical input model.

7. Implementing CRUD Operations

For a full-featured API, you'll need to implement Create, Read, Update, and Delete (CRUD) operations. This often involves interacting with a database using Entity Framework Core.

8. API Documentation with Swagger

.NET 8 includes built-in support for Swagger/OpenAPI. Ensure that Swagger is enabled in your Program.cs file:

// ... in Program.cs
app.UseSwagger();
app.UseSwaggerUI();
// ...

Access the Swagger UI at https://localhost:7041/swagger.

"The future of web development is in building efficient, scalable, and maintainable APIs. .NET 8 provides the tools and frameworks to achieve this with confidence."

Next Steps