Skip to content
  1. Blog
  2. Learning

ASP.NET Core Minimal APIs: When to Use Them and How to Build Them for Production

TL;DR: Minimal APIs let you map each route straight to a handler function, with no controller classes. They suit small to medium services, as long as you add route groups, shared validation, Problem Details errors, OpenAPI docs and tests from day one. When the API also needs eSignatures, our eSignature software development kit (SDK) for C# fits into the same project.

You have a small service to ship: a webhook receiver, an internal tool API or one slice of a larger system. A full controller project feels like too much code for five endpoints. Minimal APIs remove that extra code.

The risk comes later. Without a plan, every route lands in Program.cs, and each handler checks input in its own way. This guide builds a small starter that stays tidy as it grows.

What are Minimal APIs?

Minimal APIs are a way to build web APIs in ASP.NET Core, which joins ASP (Active Server Pages) and .NET (Microsoft’s developer platform). You map a route to a function, and that function returns the response.

Think of a small cafe with a short menu, where the person who takes your order also makes it. A controller project is more like a restaurant with waiters, a kitchen and a host. Both serve food, but the cafe needs far less setup.

Microsoft introduced Minimal APIs in .NET 6. The ASP.NET Core Minimal APIs official docs live on Microsoft Learn. Microsoft’s APIs overview now recommends them for new projects.

When should you choose Minimal APIs?

Pick Minimal APIs when the service has clear edges and your team will follow one layout for endpoint files. Both styles run on the same hosting, routing and middleware, so the choice is about structure.

Minimal APIs fit well in these cases:

  • A focused service, such as a webhook receiver, a microservice or an internal tool API.
  • A backend for frontend (BFF) that serves one web or mobile app.
  • A team that likes routes and metadata written in plain view, next to the handler.
  • A small team that can agree on route groups and one file per feature.

Controllers suit large surfaces with many domains, many contributors and existing controller templates. Our guide to controllers vs Minimal APIs in .NET 8 compares the two in depth.

What will you build in this guide?

You will build an ASP.NET Core Minimal API for a small product catalog, with route groups and an endpoint filter for validation. It also returns Problem Details errors, publishes an OpenAPI document and ships with an integration test.

Before you start, have these ready:

  • The .NET software development kit (SDK), version 9 or later, for the built-in OpenAPI support.
  • Basic C# knowledge.
  • A terminal, such as PowerShell or Bash.

Run dotnet --version in the terminal. A version number confirms the SDK works.

How does a request flow through a Minimal API?

Each Hypertext Transfer Protocol (HTTP) request passes through the same five stages. Knowing them tells you where each kind of code belongs.

  1. The request enters the middleware pipeline, where app-wide logic such as error handling runs.
  2. Routing picks the endpoint that matches the path and method.
  3. Endpoint filters run, if the endpoint has any, for checks such as validation.
  4. The handler runs and calls your services for the business logic.
  5. The result writes the response, with its status code and JavaScript Object Notation (JSON) body.

App-wide logic goes in middleware, per-feature logic goes in filters, and business rules go in services.

How do you avoid a giant Program.cs with Minimal APIs?

Give every feature its own module file and keep Program.cs for wiring only. The layout below keeps each concern in one place.

  • Program.cs registers services and middleware, then maps each module.
  • Endpoints/ holds one file per feature, each with its own route group.
  • Infrastructure/ holds shared filters, such as validation.
  • Services/ holds business logic, so handlers stay short.

With this layout, a new feature means one new file in Endpoints/. Existing endpoint files stay untouched.

How do you build the production starter step by step?

The six steps below follow the layout from the last section. Each one ends with a quick check before you move on.

Step 1: Create the project

Create an empty web project and move into its folder.

dotnet new web -n MinimalApiStarter
cd MinimalApiStarter

Run dotnet run. The server should start with no errors.

Step 2: Add OpenAPI document generation

Add Microsoft’s official OpenAPI package to the project.

dotnet add package Microsoft.AspNetCore.OpenApi

The install should finish with no errors.

Step 3: Add a service layer

Handlers turn into small controllers when they hold business logic. Put that logic in a service instead.

// Services/ProductService.cs
namespace MinimalApiStarter.Services;
public record ProductDto(int Id, string Name, decimal Price);
public record CreateProductRequest(string Name, decimal Price);
public interface IProductService
{
    Task<ProductDto?> GetAsync(int id, CancellationToken ct);
    Task<ProductDto> CreateAsync(CreateProductRequest request, CancellationToken ct);
}
public sealed class ProductService : IProductService
{
    public Task<ProductDto?> GetAsync(int id, CancellationToken ct)
        => Task.FromResult(id == 404 ? null : new ProductDto(id, "Demo", 10m));
    public Task<ProductDto> CreateAsync(CreateProductRequest request, CancellationToken ct)
        => Task.FromResult(new ProductDto(123, request.Name, request.Price));
}

The service uses no ASP.NET Core types, so you can test it on its own.

Step 4: Validate input in an endpoint filter

An endpoint filter checks the request before the handler runs. You write each rule once and attach it to any endpoint that needs it.

// Infrastructure/ValidateCreateProductFilter.cs
using Microsoft.AspNetCore.Http.HttpResults;
using MinimalApiStarter.Services;

namespace MinimalApiStarter.Infrastructure;

public sealed class ValidateCreateProductFilter : IEndpointFilter
{
    public async ValueTask<object?> InvokeAsync(
        EndpointFilterInvocationContext context,
        EndpointFilterDelegate next)
    {
        var request = context.Arguments.OfType<CreateProductRequest>().FirstOrDefault();

        if (request is null)
            return TypedResults.BadRequest(new { error = "Request body is required." });

        var errors = new Dictionary<string, string[]>();

        if (string.IsNullOrWhiteSpace(request.Name))
            errors["name"] = new[] { "Name is required." };

        if (request.Price < 0)
            errors["price"] = new[] { "Price must be >= 0." };

        if (errors.Count > 0)
            return TypedResults.ValidationProblem(errors);

        return await next(context);
    }
}

The handler for creating a product now holds no validation code.

Step 5: Define the endpoints as a feature module

A route group sets the path prefix, OpenAPI tag and authorization policy once for every endpoint in the feature.

// Endpoints/ProductsEndpoints.cs
using Microsoft.AspNetCore.Http.HttpResults;
using MinimalApiStarter.Infrastructure;
using MinimalApiStarter.Services;
namespace MinimalApiStarter.Endpoints;
public static class ProductsEndpoints
{
    public static RouteGroupBuilder MapProductsEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/api/products")
            .WithTags("Products")
            .RequireAuthorization("api");
        group.MapGet("/{id:int}", async Task<Results<Ok<ProductDto>, NotFound>> (
            int id,
            IProductService service,
            CancellationToken ct) =>
            {
                var product = await service.GetAsync(id, ct);
                return product is null ? TypedResults.NotFound() : TypedResults.Ok(product);
            })
        .Produces<ProductDto>(StatusCodes.Status200OK)
        .Produces(StatusCodes.Status404NotFound)
        .WithOpenApi();
        group.MapPost("/", async Task<Created<ProductDto>> (
            CreateProductRequest request,
            IProductService service,
            CancellationToken ct) =>
            {
                var created = await service.CreateAsync(request, ct);
                return TypedResults.Created($"/api/products/{created.Id}", created);
            })
        .AddEndpointFilter<ValidateCreateProductFilter>()
        .Produces<ProductDto>(StatusCodes.Status201Created)
        .ProducesValidationProblem()
        .WithOpenApi();
        return group;
    }
}

Check that Program.cs maps no endpoints of its own.

Step 6: Wire everything in Program.cs

Program.cs now registers services, adds middleware and maps the products module. Replace its contents with the code below.

// Program.cs
using MinimalApiStarter.Endpoints;
using MinimalApiStarter.Services;
var builder = WebApplication.CreateBuilder(args);
// OpenAPI document generation
builder.Services.AddOpenApi();
// Problem Details support (standardized error shape)
builder.Services.AddProblemDetails();
// Demo authorization policy (replace with real auth in production)
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("api", policy => policy.RequireAssertion(_ => true));
});
builder.Services.AddScoped<IProductService, ProductService>();
var app = builder.Build();
// Centralized exception handler (works well with ProblemDetails)
app.UseExceptionHandler();
app.UseAuthorization();
// Expose OpenAPI JSON endpoint
app.MapOpenApi();
// Map feature modules
app.MapProductsEndpoints();
app.Run();
// For integration tests (WebApplicationFactory)
public partial class Program { }

Run dotnet run again. The project should build and start.

How do you test and verify the API?

Start the API, then send it a few requests with curl. Each request below checks one behavior from the steps above.

Run the API locally

Start the server from the project folder.

dotnet run

Check that a GET (read) request returns a product

Request product 1. The terminal shows the port the server uses, so change 5000 to match it.

curl \
  -i \
  http://localhost:5000/api/products/1

You should see status 200 and a JSON body such as {"id":1,"name":"Demo","price":10}.

Check that a missing product returns 404

Request product 404, which the demo service treats as missing.

curl \
  -i \
  http://localhost:5000/api/products/404

You should see status 404 Not Found.

Check that the endpoint filter validates input

Send a POST (create) request with an empty name and a negative price.

curl \
  -i \
  -X POST \
  http://localhost:5000/api/products \
  -H "Content-Type: application/json" \
  -d "{\"name\":\"\",\"price\":-1}"

You should see status 400 Bad Request with a validation body from ValidationProblem. The filter stopped the request, so the handler never ran.

Check the OpenAPI document

Open /openapi/v1.json, the default path for MapOpenApi() in .NET 9 and later. The document should list /api/products/{id} and /api/products with their response types.

How do you add an integration test to prove endpoint wiring works?

Manual curl checks catch problems today, and a test catches them on every build. The test starts the whole app in memory and calls it like a real client.

Add a test project

Create an xUnit project, reference the API and add the testing package.

dotnet new xunit -n MinimalApiStarter.Tests
dotnet add MinimalApiStarter.Tests reference MinimalApiStarter
dotnet add MinimalApiStarter.Tests package Microsoft.AspNetCore.Mvc.Testing

Write the test

WebApplicationFactory uses the public partial class Program line from step 6 to find your app.

// MinimalApiStarter.Tests/ProductsApiTests.cs
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public class ProductsApiTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public ProductsApiTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task Get_Product_ReturnsOk()
    {
        var resp = await _client.GetAsync("/api/products/1");
        Assert.Equal(HttpStatusCode.OK, resp.StatusCode);
    }

    [Fact]
    public async Task Get_MissingProduct_ReturnsNotFound()
    {
        var resp = await _client.GetAsync("/api/products/404");
        Assert.Equal(HttpStatusCode.NotFound, resp.StatusCode);
    }
}

Run the tests.

dotnet test

Both tests should pass, which proves the routing and module mapping work.

What are the common production mistakes with Minimal APIs?

Most problems in a Minimal API come from skipping one of the steps above. Here are the five that show up most, with the fix for each.

Program.cs keeps growing

Endpoints were mapped straight in Program.cs as the project grew. Move each feature into its own Endpoints/*Endpoints.cs file with a Map*Endpoints() method.

Endpoints handle errors in different ways

Each handler runs its own checks and builds its own error body. Move validation into endpoint filters and return Problem Details for every error.

RequireAuthorization(“api”) throws “policy not found”

The policy was never registered, or its name differs. Make sure the name in AddPolicy("api", ...) matches the name in RequireAuthorization exactly.

The handler runs even with bad input

The validation sits inside the handler, or the filter was never attached. Confirm that .AddEndpointFilter<ValidateCreateProductFilter>() is on the endpoint or its group.

The OpenAPI endpoint returns 404

The OpenAPI services or the OpenAPI endpoint are missing. Program.cs needs both builder.Services.AddOpenApi() and app.MapOpenApi().

How do you connect other APIs to a Minimal API?

Use the other service’s official SDK, register it once with dependency injection and call it from your service layer. The handler stays short, and the SDK builds the requests and models for you.

Take a sales service that sends a contract for signature after a deal closes. Our .NET SDK wraps the BoldSign API, so ProductService would gain one method that calls it. Signing status updates can then arrive through webhooks, handled in a new feature module.

Before you go live, swap the demo policy for real sign-in. Our ASP.NET Core JSON Web Token (JWT) authentication guide walks through it. Then check your endpoints against the API Security Top 10 from the Open Worldwide Application Security Project (OWASP).

What does it cost to add the BoldSign API to your Minimal API?

You can build and test the whole integration for free in a sandbox, with no credit card. Live sending needs the Enterprise API plan, which starts at $30 a month with 40 envelopes.

Each extra envelope costs $0.75, as listed on the BoldSign pricing page in November 2026. Prices are in USD. Sandbox documents carry a watermark, and we delete them after 14 days.

Where do you go next with your Minimal API?

Your starter now has route groups, shared validation, consistent errors, OpenAPI docs and a test. Pick the next step that fits your project.

Frequently asked questions

Is an ASP.NET Minimal API ready for production?

Yes. Microsoft now recommends Minimal APIs for new HTTP API projects. Add route groups, shared validation and consistent errors early, then cover the wiring with tests.

Where are the ASP.NET Core Minimal APIs official docs?

They are on Microsoft Learn, under ASP.NET Core fundamentals. Start with the Minimal APIs quick reference, then read the pages on filters, route groups and OpenAPI.

Which .NET version introduced Minimal APIs?

.NET 6 introduced Minimal APIs. Microsoft announced them in the release notes called What's new in ASP.NET Core 6.0 on Microsoft Learn, which link to the first Minimal API tutorial.

What has changed in Minimal APIs since .NET 6?

ASP.NET Core 7.0 added endpoint filters and route groups. In .NET 9, ASP.NET Core added built-in OpenAPI document generation through AddOpenApi and MapOpenApi.

Is the .NET 6 documentation for Minimal APIs still current?

Partly. Microsoft Learn keeps one page per version, so pick your target version in the version selector. Newer versions cover features that the 6.0 pages lack.

How do I return consistent error shapes from Minimal APIs?

Register AddProblemDetails and UseExceptionHandler, then return ValidationProblem for bad input. Every error then shares one JSON shape, and internal exception details stay on the server.

Should I use middleware or endpoint filters for shared logic?

Use middleware for logic every request needs, such as error handling and headers. Use endpoint filters for logic one endpoint or route group needs, such as validation.

How to connect APIs with minimal development work in .NET?

Call the other service through its official .NET SDK, registered once with dependency injection. For eSignatures, our .NET SDK wraps the BoldSign API, so a handler needs only a few lines.

Priya Vinayagam

Priya Vinayagam is a Product Manager at BoldSign and an active full-stack developer at Syncfusion, with four years of hands-on experience across .NET and JavaScript. She writes practical, performance-focused technical articles that help developers tackle real-world challenges. Known for looking beyond the obvious, Priya brings a builder’s mindset to every post—breaking down complex problems into clear, actionable solutions. Connect with her on LinkedIn.

More posts by Priya Vinayagam
Get started

Sign up for your free trial today!

Start free trial
  • 30-day free trial
  • No credit card required