You've built a Web API. It works. But now a teammate asks, "What endpoints do we have? What do they return?" and you find yourself pasting Postman screenshots into Slack.
There's a better way: Swagger. In a few minutes you can give your C# Web API a live, interactive documentation page where anyone can read and test every endpoint from the browser.
This guide shows you how to add Swagger to an ASP.NET Core Web API, step by step, with real code and fixes for the problems people usually hit.
What Is Swagger (and Why Should You Care)?
Swagger is a set of tools built around the OpenAPI Specification, a standard way to describe REST APIs. In the .NET world, "adding Swagger" usually means two things:
- A generated OpenAPI document (a JSON file describing your endpoints, parameters, and responses)
- Swagger UI, a web page that turns that JSON into clickable, testable documentation
The benefits:
- Docs stay in sync with your code automatically
- Front-end developers and testers can try endpoints without extra tools
- Client code can be generated from the OpenAPI file
- Onboarding new developers gets much faster
Before You Start
You'll need:
- The .NET SDK (6 or later, ideally the latest LTS)
- Visual Studio, VS Code, or Rider
- An ASP.NET Core Web API project (or create one below)
To create a new project from the terminal:
dotnet new webapi -n MyApi
cd MyApi
Note: Older templates (.NET 5–8) included Swagger by default. Starting with .NET 9, the default template ships with Microsoft's built-in OpenAPI support but no Swagger UI. That's why many people now search for how to add it manually.
Method 1: Add Swagger with Swashbuckle (Most Popular)
Swashbuckle is the long-standing library that generates the OpenAPI document and serves Swagger UI.
Step 1: Install the NuGet package
Using the CLI:
dotnet add package Swashbuckle.AspNetCore
Or in Visual Studio: right-click your project, choose Manage NuGet Packages, search for Swashbuckle.AspNetCore, and install it.
Step 2: Register Swagger services
Open Program.cs and add these lines before builder.Build():
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
AddEndpointsApiExplorer() helps Swagger discover your endpoints (especially minimal APIs), and AddSwaggerGen() generates the OpenAPI document.
Step 3: Enable the middleware
Add this after Build():
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Step 4: Run and open Swagger UI
dotnet run
Then visit:
https://localhost:{port}/swagger
You should see every controller and endpoint listed, each with a Try it out button. The raw OpenAPI JSON lives at /swagger/v1/swagger.json.
That's the core setup. Now let's make it genuinely useful.
Customize Your Swagger Documentation
Default docs work, but a little polish makes them far more helpful.
Add API title, version, and description
using Microsoft.OpenApi.Models;
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Title = "My Awesome API",
Version = "v1",
Description = "An API for managing products and orders.",
Contact = new OpenApiContact
{
Name = "Dev Team",
Email = "[email protected]"
}
});
});
If your Swashbuckle version uses a newer Microsoft.OpenApi release, the
usingnamespace may differ (Microsoft.OpenApi). Your IDE's quick-fix will point you to the right one.
Show XML comments as descriptions
This is the trick that turns your code comments into real documentation.
1. Enable XML documentation in your .csproj:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
2. Tell Swagger to read the file:
builder.Services.AddSwaggerGen(options =>
{
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
});
3. Comment your endpoints:
/// <summary>
/// Gets a product by its ID.
/// </summary>
/// <param name="id">The product identifier.</param>
/// <returns>The matching product.</returns>
/// <response code="200">Product found.</response>
/// <response code="404">Product does not exist.</response>
[HttpGet("{id}")]
[ProducesResponseType(typeof(Product), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetProduct(int id) { ... }
Add using System.Reflection; at the top if you haven't already.
Serve Swagger UI at the root URL
If you'd rather open https://localhost:{port}/ and land straight on the docs:
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My Awesome API v1");
options.RoutePrefix = string.Empty;
});
Add JWT Authentication to Swagger
If your API uses bearer tokens, Swagger UI needs an Authorize button so you can test protected endpoints.
builder.Services.AddSwaggerGen(options =>
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = "bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "Enter your JWT token."
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
Array.Empty<string>()
}
});
});
Run the app, click Authorize, paste your token, and every request from Swagger UI will include it.
Method 2: Use Built-In OpenAPI Support (.NET 9 and Later)
Microsoft now ships its own OpenAPI document generation in the framework, so Swashbuckle is optional. The built-in package only generates the OpenAPI JSON; it doesn't include a UI, so you pair it with Swagger UI, Scalar, or similar.
dotnet add package Microsoft.AspNetCore.OpenApi
dotnet add package Swashbuckle.AspNetCore.SwaggerUI
builder.Services.AddOpenApi();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/openapi/v1.json", "My API v1");
});
}
Which should you pick?
| Swashbuckle (Method 1) | Built-in OpenAPI (Method 2) | |
|---|---|---|
| Setup | One package, very familiar | Slightly more manual |
| UI included | Yes | No, add your own |
| Long-term direction | Community-maintained | Microsoft's default path |
| Best for | Existing projects, quick setup | New .NET 9+ projects |
If you want the fastest path and the most tutorials to lean on, go with Swashbuckle. If you're starting fresh on a recent .NET version, the built-in option is worth a look.
Common Swagger Errors (and Quick Fixes)
Swagger page shows 404.
Check that UseSwagger() and UseSwaggerUI() are called, and that you're running in the Development environment (or remove the IsDevelopment() check).
"Failed to load API definition" or "Fetch error."
Open /swagger/v1/swagger.json directly. The error message there usually names the real problem, often an endpoint that Swagger can't process.
"Conflicting method/path combination" error.
Two actions share the same route and HTTP verb. Change one route or add [ApiExplorerSettings(IgnoreApi = true)] to hide it.
Missing endpoints.
Make sure controllers have [ApiController] and an explicit HTTP attribute like [HttpGet]. For minimal APIs, call AddEndpointsApiExplorer().
XML comments not showing.
Confirm GenerateDocumentationFile is true and that the XML file path in IncludeXmlComments matches your assembly name.
Best Practices for Swagger in Production
- Think before exposing it publicly. Many teams enable Swagger only in Development or Staging. If you do expose it, protect it behind authentication.
- Document your response codes with
[ProducesResponseType]so consumers know what to expect. - Version your API and publish one Swagger doc per version.
- Keep summaries short and clear. Write them for someone who has never seen your code.
Frequently Asked Questions
How do I add Swagger to an existing ASP.NET Core Web API?
Install Swashbuckle.AspNetCore, call AddSwaggerGen() in your service registration, then UseSwagger() and UseSwaggerUI() in the pipeline. That's it.
Is Swagger the same as OpenAPI?
Not exactly. OpenAPI is the specification; Swagger is the toolset (including Swagger UI) that works with it. In casual conversation, people use the words interchangeably.
Why is Swagger missing from my new .NET project?
Newer .NET templates no longer include Swashbuckle by default. Add it manually using the steps above.
Can I use Swagger with minimal APIs?
Yes. Use AddEndpointsApiExplorer() along with AddSwaggerGen(), and your minimal API endpoints will appear.
Is Swagger free?
Swashbuckle and Swagger UI are open source and free to use.