David's Blog

Swashbuckle Simplifying API Documentation in C#

By David Li on 2023-04-24T18:13:58.176Z

Swashbuckle: Simplifying API Documentation in C#

Swashbuckle is a powerful library that helps developers in creating, maintaining, and integrating API documentation with their C# applications. In this article, we will explore the features and capabilities of Swashbuckle, and learn how to integrate it seamlessly into a C# project. Swashbuckle utilizes the OpenAPI Specification (formerly known as Swagger) to generate interactive API documentation and client SDKs.

Table of Contents

  1. Introduction to Swashbuckle
  2. Integrating Swashbuckle into a C# Project
  3. Configuring Swashbuckle
  4. Adding XML Comments to API Documentation
  5. Customizing Swagger UI
  6. Conclusion

Introduction to Swashbuckle

Swashbuckle is an open-source project that combines multiple libraries to provide seamless integration of Swagger (OpenAPI) with .NET projects. The main components of Swashbuckle include:

  • Swashbuckle.AspNetCore.Swagger: Generates Swagger (OpenAPI) documents for your APIs.
  • Swashbuckle.AspNetCore.SwaggerGen: Provides a set of capabilities to customize and extend the generated Swagger documents.
  • Swashbuckle.AspNetCore.SwaggerUI: Embeds an interactive Swagger UI in your application, allowing users to explore and test the API.

Integrating Swashbuckle into a C# Project

To get started with Swashbuckle, first, add the necessary NuGet packages to your project. You can do this by executing the following commands in your terminal or package manager console:

dotnet add package Swashbuckle.AspNetCore

Or, through the NuGet Package Manager in Visual Studio, search for “Swashbuckle.AspNetCore” and install the package.

Next, update the Startup.cs file to enable Swashbuckle middleware. Add the following lines of code in the ConfigureServices method:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});

And add the following lines in the Configure method to enable the middleware for serving the generated JSON document and the Swagger UI:

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
});

Now, run your application and navigate to the Swagger UI by adding /swagger to your application’s base URL (e.g., https://localhost:5001/swagger).

Configuring Swashbuckle

Swashbuckle provides various configuration options to customize the generated Swagger document. Some of the most commonly used options include:

  • Operation Filters: Allows you to modify individual API operations.
  • Document Filters: Allows you to modify the entire Swagger document.
  • Schema Filters: Allows you to modify individual schema definitions.

For example, to include XML comments in your Swagger document, you need to configure Swashbuckle to read XML comments generated by the C# compiler. Update the SwaggerGen configuration in the Startup.cs file as follows:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });

    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});

Adding XML Comments to API Documentation

To add XML comments to your API documentation, you need to configure your project to generate an XML documentation file. Open your project’s .csproj file and add the following property inside the <PropertyGroup>:

<GenerateDocumentationFile>true</GenerateDocumentationFile>

Now, add XML comments to your API controllers and actions, like this:

/// <summary>
/// Retrieves a list of all items.
/// </summary>
[HttpGet]
public ActionResult<IEnumerable<Item>> GetItems()
{
    // ...
}

Customizing Swagger UI

Swashbuckle allows you to customize the appearance and behavior of the Swagger UI. To do this, update the SwaggerUI configuration in the Startup.cs file as follows:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API v1");
    c.DocumentTitle = "My API - Documentation";
    c.RoutePrefix = "docs";
    c.InjectStylesheet("/css/custom-swagger.css");
    c.EnableDeepLinking();
    c.DisplayRequestDuration();
});

Here, we have changed the document title, set a custom route prefix, injected a custom stylesheet, enabled deep linking, and set the request duration display for the Swagger UI.

Conclusion

Swashbuckle is an invaluable tool for C# developers, providing a straightforward and efficient way to generate interactive API documentation using the OpenAPI Specification. By integrating Swashbuckle into your C# project, you can easily maintain up-to-date documentation and help users explore and test your API. Additionally, Swashbuckle’s extensive configuration options allow you to tailor the generated documentation and Swagger UI to your specific needs, ensuring a seamless and professional experience for your API users.

© Copyright 2024 by FriendlyUsers Tech Blog. Built with ♥ by FriendlyUser. Last updated on 2024-11-21.