Create a Minimal Web API with .NET Core
This tutorial walks you through building a simple RESTful Web API using .NET 8 minimal APIs.
Prerequisites
- Visual Studio 2022 or VS Code
- .NET SDK 8.0 or later
- Basic knowledge of C# and HTTP
Step 1 – Create a New Project
Open a terminal and run:
dotnet new webapi -o WeatherApi
Navigate to the project folder:
cd WeatherApi
Step 2 – Define a Model
Create a file Models/WeatherForecast.cs
with the following content:
namespace WeatherApi.Models;
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string? Summary { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Step 3 – Add the Endpoint
Edit Program.cs
to expose a GET endpoint:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" };
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherApi.Models.WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = summaries[Random.Shared.Next(summaries.Length)]
})
.ToArray();
return forecast;
});
app.Run();
Step 4 – Run the API
Start the application:
dotnet run
Open a browser and navigate to http://localhost:5042/weatherforecast to see the JSON response.