Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to How To Guides
How to Build a Web API in .NET

How to Build a Web API in .NET

How To Guides2,839 viewsBy Admin
dot-netbuild

Build a Minimal Web API

.NET makes it incredibly easy to spin up a JSON API with minimal code.

Step 1: Create the Project

dotnet new webapi -n MyApi
cd MyApi
dotnet run

Step 2: Minimal API Endpoints

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

var todos = new List<string> { "Learn .NET" };

app.MapGet("/todos", () => todos);
app.MapPost("/todos", (string item) => {
    todos.Add(item);
    return Results.Created($"/todos/{item}", item);
});

app.Run();

Step 3: Controller-Based (Larger Apps)

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase {
    [HttpGet]
    public IActionResult Get() => Ok(_service.GetAll());

    [HttpPost]
    public IActionResult Create(Product p) {
        _service.Add(p);
        return CreatedAtAction(nameof(Get), p);
    }
}

Step 4: Test with Swagger

.NET Web API templates include Swagger UI at /swagger automatically to test endpoints.

FAQs

Minimal API or controllers?

Minimal for small services, controllers for large structured apps. More in our .NET guides.

How do I add a database?

Use Entity Framework Core with dependency injection.