Getting Started with the Latest .NET for Building Web APIs — A Friendly Guide
You’re in the right place if you’ve been interested in using .NET to create Web APIs but are unsure where to begin. This tutorial will show you how to use the most recent version of .NET (currently .NET 9) to create a straightforward, useful API, regardless of whether you’ve worked with earlier iterations of the framework or are entirely unfamiliar with it.
It’s not just about throwing code at you; it’s also about giving you a basic, developer-friendly understanding of what’s going on behind the scenes.
Why Choose .NET for Web APIs?
Although there are numerous frameworks available for creating APIs, .NET constantly sticks out for a few reasons.
It’s cross-platform, which means you don’t need to make any changes to build and run apps on Windows, Linux, or macOS. Additionally, it is based on C#, a language renowned for striking a balance between simplicity and power.
Dependency injection, configuration, middleware, and outstanding performance right out of the box are just a few of the many free benefits that come with DOTNET. The ecosystem surrounding Visual Studio, VS Code, and CLI is established and well-maintained, and the tooling itself is excellent.
.NET has gotten faster and more developer-friendly with every release. With improved native AOT (Ahead-of-Time compilation), improved startup performance, and improvements to the minimal API experience, the most recent version carries on that trend.
Before You Begin
you don’t need much to get started:
- Install the .NET SDK (version 9) from Microsoft’s website.
- Have a code editor ready — Visual Studio or VS Code are great options.
- Make sure you’re familiar with basic C# syntax and have a general idea of how HTTP and REST APIs work.
Once that’s done, you’re ready to create your first API.
Step 1: Create a New Project
You can create a new Web API project using either the command line or Visual Studio. Both are fine — it really depends on what you’re comfortable with.
Using the Command Line
Open your terminal and run:
dotnet new webapi -n MyApi --framework net9.0
This creates a new project with a ready-to-run Web API template.
If you prefer the traditional controller-based structure (instead of minimal APIs), you can add:
--use-controllers That will give you a familiar Controllers folder and a sample controller class to start from.
Using Visual Studio
If you’re using Visual Studio, go to
File → New → Project → ASP.NET Core Web API.
Select the latest .NET version, give your project a name, and make sure “Enable OpenAPI support” is checked. That automatically adds Swagger, which helps you test your endpoints visually later.
Step 2: Understanding the Structure
Once the project is created, open it up and take a look around.
The most important file is Program.cs — it’s where the app is configured and started. In newer .NET versions, there’s no separate Startup.cs anymore. Everything happens in one place.
Here’s what it might look like:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
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();
If you’re wondering what’s happening here —
- The first few lines configure services like controllers and Swagger.
- The middle section sets up middleware (things that handle requests and responses).
- The last part actually maps your routes and starts the application.
Step 3: Build a Simple API
Let’s make something real — a small “To-Do List” API.
The Model
Start by creating a simple class to represent a task:
public class TodoItem
{
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public bool IsComplete { get; set; }
}
A Temporary Data Store
For now, let’s use an in-memory list to store items:
public static class TodoRepository
{
private static readonly List<TodoItem> Items = new();
public static IEnumerable<TodoItem> GetAll() => Items;
public static TodoItem? Get(int id) => Items.FirstOrDefault(i => i.Id == id);
public static void Add(TodoItem item) => Items.Add(item);
public static void Delete(int id) => Items.RemoveAll(i => i.Id == id);
}
The Controller
Now, create a new file named TodoController.cs inside the Controllers folder:
[ApiController]
[Route("api/[controller]")]
public class TodoController : ControllerBase
{
[HttpGet]
public IActionResult GetAll() => Ok(TodoRepository.GetAll());
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var item = TodoRepository.Get(id);
return item is null ? NotFound() : Ok(item);
}
[HttpPost]
public IActionResult Create(TodoItem item)
{
item.Id = TodoRepository.GetAll().Count() + 1;
TodoRepository.Add(item);
return CreatedAtAction(nameof(GetById), new { id = item.Id }, item);
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
TodoRepository.Delete(id);
return NoContent();
}
}
Now run the app (dotnet run or press F5 in Visual Studio).
Your API should be live at https://localhost:5001/swagger, and you’ll see all your endpoints ready to test.
Step 4: Connect to a Database (Optional)
Using an in-memory list is fine for demos, but real APIs use a database. The most common choice is Entity Framework Core.
Install the necessary packages:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Then create a DbContext:
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options)
: base(options) { }
public DbSet<TodoItem> TodoItems => Set<TodoItem>();
}
Register it inside Program.cs:
builder.Services.AddDbContext<TodoContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
And add your connection string to appsettings.json.
Once done, you can use EF migrations to create and manage your database schema. This allows your API to persist data between runs.
Step 5: Adding the Essentials
Once your core endpoints work, you’ll want to add the features that make your API production-ready:
- Validation: Use data annotations like [Required], [MaxLength], and [Range] to ensure inputs are valid.
- Error handling: You can add global exception middleware or use UseExceptionHandler to catch and format errors.
- CORS: Enable it if your API will be accessed from a frontend app running on another domain.
- Authentication: ASP.NET Core supports JWT, OAuth, and cookie-based authentication out of the box.
- Logging: Built-in logging works great, or you can plug in Serilog or NLog for advanced scenarios.
Step 6: Deploying Your API
When your API is ready, you can publish it anywhere .NET runs — which is practically everywhere.
You can host it on:
- Azure App Service
- AWS Elastic Beanstalk
- Docker
- A Linux or Windows server
To publish, run:
dotnet publish -c Release This builds your project for deployment. You can then copy the output files or containerize the app using Docker.
Step 7: Where to Go from Here
You’ve just built a working Web API with .NET — congratulations!
From here, you might explore:
- Structuring larger applications using Clean Architecture or DDD.
- Adding caching (Redis or MemoryCache) to improve performance.
- Implementing API versioning for backward compatibility.
- Adding integration and unit tests to ensure reliability.
- Using Swagger/OpenAPI for proper documentation.
The key is to start small, understand the building blocks, and then scale your design as the application grows.
Final Thoughts
Building Web APIs with .NET has become incredibly streamlined over the years. With the latest .NET release, Microsoft has made it easier to create fast, clean, and reliable APIs without unnecessary boilerplate.
If you already know C#, you’ll find yourself productive within a day. And even if you’re new, the learning curve is gentle — you’ll be deploying your first API before you know it.
Once you’re comfortable, you can explore advanced topics like background jobs, authentication systems, or microservices built on top of this same foundation.
