Skip to main content

How to Add Swagger in Web API C# (Step-by-Step Guide)

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 using namespace 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.

Popular posts from this blog

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

C++ vcpkg Manifest Mode + CMake

 If you've ever tried to install a C++ library and felt like you were assembling furniture without instructions, this article is for you. We're going to talk about vcpkg manifest mode and how it works with CMake , and I'm going to explain it like you're five years old (in a good way — no judgment here). First, Let's Talk About the Problem In most programming languages, adding a library is easy. Python has pip install requests . JavaScript has npm install express . You type one command, and boom, the library shows up in your project. C++ never really had that. For decades, if you wanted to use a library like fmt or nlohmann/json , you had to: Download the source code yourself Figure out how to compile it Tell your compiler where to find the headers Tell your linker where to find the compiled binaries Cry a little vcpkg is Microsoft's answer to this mess. It's a package manager for C++ — like pip or npm , but for C++ libraries. And manifest mode...

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...