
Table of contents
- Introduction
- Understanding Swagger, OpenAPI, and related terms
- Main libraries for .NET Swagger documentation
- Getting started with Swashbuckle in ASP.NET Core
- Enriching your API documentation
- Working with NSwag
- Microsoft.AspNetCore.OpenAPI in .NET 9
- Comparison of Swagger tooling options
- Best practices for Swagger documentation
- Conclusion
- Need expert help with your API documentation?
- Resources
Introduction
API documentation is a crucial aspect of modern web development, providing clear instructions on how to interact with your services. In the .NET ecosystem, Swagger (now known as OpenAPI) has become the standard for documenting RESTful APIs. Swagger/OpenAPI is a language-agnostic specification for describing REST APIs that allows both computers and humans to understand API capabilities without access to the source code. This article explores the tools and approaches available for implementing Swagger documentation in .NET applications, including the popular Swashbuckle library and alternatives.
Understanding Swagger, OpenAPI, and related terms
Before diving into implementation details, it’s important to understand the terminology:
-
OpenAPI Specification: A language-agnostic standard for describing REST APIs. The Swagger project was donated to the OpenAPI Initiative in 2015 and has since been referred to as OpenAPI, though both names are still used interchangeably.
-
Swagger: Refers to the family of open-source and commercial products from SmartBear that work with the OpenAPI Specification. When developers talk about “Swagger,” they’re typically referring to the tools that help generate, visualize, and consume OpenAPI documentation.
-
Swagger UI: A web-based interface that renders OpenAPI specifications as interactive documentation, allowing developers to explore and test API endpoints directly in the browser.
Main libraries for .NET Swagger documentation
Swashbuckle.AspNetCore
Swashbuckle is the most widely used library for implementing Swagger in ASP.NET Core applications. It consists of three main components:
- Swashbuckle.AspNetCore.Swagger: A middleware that exposes Swagger documents as JSON endpoints
- Swashbuckle.AspNetCore.SwaggerGen: A generator that builds Swagger documents directly from your routes, controllers, and models
- Swashbuckle.AspNetCore.SwaggerUI: An embedded version of the Swagger UI tool that provides an interactive experience for your API documentation
Swashbuckle automatically analyzes your API controllers and routes to generate documentation, and can be enhanced with XML comments and attributes to provide more detailed information.
NSwag
NSwag is another powerful toolchain for .NET, .NET Core, Web API, and ASP.NET Core that supports both Swagger/OpenAPI 2.0 and 3.0 specifications. It provides similar functionality to Swashbuckle, but with some key differences:
While Swashbuckle focuses primarily on generating API documentation, NSwag combines the functionality of API documentation generation with client code generation capabilities. This makes it particularly useful for teams that need to generate client libraries to consume their APIs.
NSwag provides:
- Tools to generate OpenAPI specifications from ASP.NET Web API controllers
- Middleware for serving the specifications via ASP.NET Core
- Utilities to generate client code in C# or TypeScript from these specifications
Microsoft.AspNetCore.OpenAPI (New in .NET 9)
With the release of .NET 9, Microsoft introduced built-in support for OpenAPI document generation through the Microsoft.AspNetCore.OpenAPI package. This move aims to make OpenAPI a first-class citizen in the .NET ecosystem.
The new package provides several features:
- Support for generating OpenAPI version 3.1 documents
- Support for JSON Schema draft 2020-12
- Runtime OpenAPI document generation
- “Transformer” APIs for document modification
- Support for multiple OpenAPI documents from a single app
- Compatibility with native AOT compilation
Getting started with Swashbuckle in ASP.NET Core
To implement Swagger documentation using Swashbuckle in an ASP.NET Core project, follow these steps:
-
Install the necessary packages:
dotnet add package Swashbuckle.AspNetCore
-
Configure services in Program.cs:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();
-
Enable the middleware:
var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }
-
Launch your application and navigate to /swagger to see your API documentation.
Enriching your API documentation
Basic Swagger integration provides minimal information about your API endpoints. To create more useful documentation, you can enhance it in several ways:
Adding XML comments
To enhance generated docs with human-friendly descriptions, you can annotate controller actions and models with XML comments and configure Swashbuckle to incorporate those comments:
-
Enable XML documentation file generation in your project file:
<PropertyGroup> <GenerateDocumentationFile>true</GenerateDocumentationFile> <NoWarn>1591</NoWarn> </PropertyGroup>
-
Configure Swashbuckle to use the XML file:
builder.Services.AddSwaggerGen(c => { var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); });
-
Add XML comments to your controllers:
/// <summary> /// Creates a new item /// </summary> /// <param name="item">Item data</param> /// <returns>The created item</returns> /// <remarks> /// Sample request: /// /// POST /api/items /// { /// "name": "Item 1", /// "description": "This is an item" /// } /// /// </remarks> [HttpPost] public ActionResult<Item> Create(Item item)
Using Swashbuckle annotations
For more advanced documentation needs, you can use annotations packages like Swashbuckle.AspNetCore.Annotations, which allows you to:
- Add metadata for operations, parameters, responses, and schemas
- Specify security requirements
- Add custom request and response headers
Adding request and response examples
The Swashbuckle.AspNetCore.Filters package provides functionalities to significantly improve API documentation with request and response examples:
- Install the Swashbuckle.AspNetCore.Filters package
- Enable example filters in configuration
- Implement IExamplesProvider to create example data objects
Working with NSwag
NSwag offers an alternative approach to Swagger documentation in .NET applications.
Setting up NSwag in ASP.NET Core
-
Install the package:
dotnet add package NSwag.AspNetCore
-
Configure services:
builder.Services.AddOpenApiDocument(config => { config.PostProcess = document => { document.Info.Version = "v1"; document.Info.Title = "Sample API"; document.Info.Description = "A simple ASP.NET Core web API"; }; });
-
Enable the middleware:
app.UseOpenApi(); app.UseSwaggerUi3();
Using NSwagStudio
NSwagStudio is a Windows desktop application that provides a UI for generating client code from OpenAPI specifications. It allows you to:
- Import your Swagger/OpenAPI specification
- Generate client code in C# or TypeScript
- Customize the generated code
- Generate server-side controllers (reverse engineering)
Microsoft.AspNetCore.OpenAPI in .NET 9
With the release of .NET 9, Microsoft has moved away from including Swagger/Swashbuckle by default in Web API templates, introducing a native solution through Microsoft.AspNetCore.OpenAPI. This change addresses several concerns:
- Maintenance issues with third-party libraries
- Compatibility with Native AOT
- Integration with the .NET ecosystem
- Performance and startup time
Setting up OpenAPI in .NET 9
-
Use the built-in functionality:
var builder = WebApplication.CreateBuilder(); builder.Services.AddOpenApi(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.MapOpenApi(); }
-
Access your OpenAPI document at
/openapi/v1.json
Using a UI with .NET 9 OpenAPI
The Microsoft.AspNetCore.OpenAPI package doesn’t ship with built-in support for visualizing the OpenAPI document. To add a UI:
- Install the Swashbuckle.AspNetCore.SwaggerUI package (just the UI component)
- Configure the middleware:
app.UseSwaggerUI(options => { options.SwaggerEndpoint("/openapi/v1.json", "v1"); });
Alternatively, you can use modern alternatives like:
- Scalar UI: An open-source interactive API documentation UI for OpenAPI
- ReDoc: A responsive, customizable documentation UI
Comparison of Swagger tooling options
Feature | Swashbuckle | NSwag | Microsoft.AspNetCore.OpenAPI |
---|---|---|---|
OpenAPI version support | 2.0 and 3.0 | 2.0 and 3.0 | 3.1 |
UI included | Yes (Swagger UI) | Yes (Swagger UI and ReDoc) | No (requires separate package) |
Client code generation | No | Yes (C# and TypeScript) | No |
Native AOT compatibility | Limited | Limited | Full |
Maintenance status | Community-maintained | Active | Microsoft-maintained |
XML documentation support | Yes | Yes | Not yet (planned) |
Best practices for Swagger documentation
- Use descriptive summaries and remarks for endpoints
- Document all possible response codes (success and error)
- Provide examples for request and response models
- Group related endpoints using tags
- Secure your Swagger UI in production environments
- Keep documentation up-to-date with API changes
- Include authentication information where required
Conclusion
Effective API documentation is crucial for the success of your services, and the .NET ecosystem offers several robust options for implementing Swagger/OpenAPI specifications. Whether you choose Swashbuckle, NSwag, or the new Microsoft.AspNetCore.OpenAPI package, investing time in proper documentation will pay dividends in developer productivity and API adoption.
With the evolution towards native OpenAPI support in .NET 9, the future of API documentation in the .NET ecosystem looks promising, with better integration, performance, and compatibility with modern deployment scenarios like Native AOT.
Need expert help with your API documentation?
Ready to take your API documentation to the next level? Weesho Lapara offers expert consulting services for .NET Swagger implementation and optimization. With years of experience in API design and documentation, Weesho can help you:
- Set up and configure the right Swagger tooling for your needs
- Enhance your existing API documentation with best practices
- Implement custom Swagger extensions and integrations
- Train your team on effective API documentation workflows
Contact Weesho Lapara today at support@weesholapara.com or visit weesholapara.com/book to schedule a consultation and transform your API documentation experience!