blog-main-1

Table of contents

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.

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:

  1. Swashbuckle.AspNetCore.Swagger: A middleware that exposes Swagger documents as JSON endpoints
  2. Swashbuckle.AspNetCore.SwaggerGen: A generator that builds Swagger documents directly from your routes, controllers, and models
  3. 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:

  1. Install the necessary packages:

    dotnet add package Swashbuckle.AspNetCore
  2. Configure services in Program.cs:

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddControllers();
    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();
  3. Enable the middleware:

    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    }
  4. 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:

  1. Enable XML documentation file generation in your project file:

    <PropertyGroup>
      <GenerateDocumentationFile>true</GenerateDocumentationFile>
      <NoWarn>1591</NoWarn>
    </PropertyGroup>
  2. 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);
    });
  3. 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:

  1. Install the Swashbuckle.AspNetCore.Filters package
  2. Enable example filters in configuration
  3. 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

  1. Install the package:

    dotnet add package NSwag.AspNetCore
  2. 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";
        };
    });
  3. 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:

  1. Import your Swagger/OpenAPI specification
  2. Generate client code in C# or TypeScript
  3. Customize the generated code
  4. 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:

  1. Maintenance issues with third-party libraries
  2. Compatibility with Native AOT
  3. Integration with the .NET ecosystem
  4. Performance and startup time

Setting up OpenAPI in .NET 9

  1. Use the built-in functionality:

    var builder = WebApplication.CreateBuilder();
    builder.Services.AddOpenApi();
    
    var app = builder.Build();
    
    if (app.Environment.IsDevelopment())
    {
        app.MapOpenApi();
    }
  2. 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:

  1. Install the Swashbuckle.AspNetCore.SwaggerUI package (just the UI component)
  2. 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

FeatureSwashbuckleNSwagMicrosoft.AspNetCore.OpenAPI
OpenAPI version support2.0 and 3.02.0 and 3.03.1
UI includedYes (Swagger UI)Yes (Swagger UI and ReDoc)No (requires separate package)
Client code generationNoYes (C# and TypeScript)No
Native AOT compatibilityLimitedLimitedFull
Maintenance statusCommunity-maintainedActiveMicrosoft-maintained
XML documentation supportYesYesNot yet (planned)

Best practices for Swagger documentation

  1. Use descriptive summaries and remarks for endpoints
  2. Document all possible response codes (success and error)
  3. Provide examples for request and response models
  4. Group related endpoints using tags
  5. Secure your Swagger UI in production environments
  6. Keep documentation up-to-date with API changes
  7. 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!

Resources