Convert Figma logo to code with AI

domaindrivendev logoSwashbuckle.AspNetCore

Swagger tools for documenting API's built on ASP.NET Core

5,380
1,336
5,380
181

Top Related Projects

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

24,727

📘 OpenAPI/Swagger-generated API Reference Documentation

4,651

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

7,118

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.

Automated JSON API documentation for API's built with Spring

Quick Overview

Swashbuckle.AspNetCore is a popular open-source library for generating Swagger/OpenAPI documentation for ASP.NET Core Web APIs. It automatically generates API documentation and provides a user-friendly interface for exploring and testing API endpoints.

Pros

  • Easy integration with ASP.NET Core projects
  • Automatic generation of OpenAPI documentation
  • Customizable UI for API exploration and testing
  • Supports authentication and authorization schemes

Cons

  • Can increase project build time and size
  • May require additional configuration for complex API scenarios
  • Documentation generation might not capture all nuances of custom implementations
  • Learning curve for advanced customization options

Code Examples

  1. Basic Swagger configuration in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
}
  1. Adding XML comments to API documentation:
services.AddSwaggerGen(c =>
{
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    c.IncludeXmlComments(xmlPath);
});
  1. Customizing Swagger UI:
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    c.RoutePrefix = string.Empty;
    c.DocExpansion(DocExpansion.None);
    c.DefaultModelsExpandDepth(-1);
});

Getting Started

  1. Install the NuGet package:

    dotnet add package Swashbuckle.AspNetCore
    
  2. Add Swagger services in Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
        });
    }
    
  3. Configure Swagger middleware in Startup.cs:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"));
    }
    
  4. Run your application and navigate to /swagger to view the Swagger UI.

Competitor Comparisons

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.

Pros of swagger-ui

  • More flexible and customizable UI for API documentation
  • Can be used with various backend frameworks and languages
  • Larger community and more frequent updates

Cons of swagger-ui

  • Requires more setup and configuration compared to Swashbuckle.AspNetCore
  • Less integrated with ASP.NET Core ecosystem
  • May need additional tools or libraries for generating OpenAPI specifications

Code Comparison

Swashbuckle.AspNetCore (in Startup.cs):

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

swagger-ui (in HTML):

<script src="https://unpkg.com/swagger-ui-dist@3/swagger-ui-bundle.js"></script>
<script>
    const ui = SwaggerUIBundle({
        url: "https://petstore.swagger.io/v2/swagger.json",
        dom_id: '#swagger-ui',
    })
</script>

Swashbuckle.AspNetCore is tightly integrated with ASP.NET Core, providing automatic OpenAPI specification generation and UI setup. swagger-ui offers more flexibility but requires manual configuration and separate specification generation. Swashbuckle.AspNetCore is ideal for ASP.NET Core projects, while swagger-ui is better suited for multi-language environments or when more customization is needed.

OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)

Pros of openapi-generator

  • Supports multiple programming languages and frameworks, not limited to .NET
  • Generates both client and server code from OpenAPI specifications
  • Offers a wider range of customization options and templates

Cons of openapi-generator

  • Steeper learning curve due to its broader scope and complexity
  • May require more setup and configuration for specific use cases
  • Less seamless integration with ASP.NET Core projects compared to Swashbuckle

Code Comparison

Swashbuckle.AspNetCore:

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

openapi-generator:

openapi-generator generate -i petstore.yaml -g csharp-netcore -o /tmp/csharp-netcore

The Swashbuckle example shows how to add Swagger documentation to an ASP.NET Core project, while the openapi-generator example demonstrates generating C# code from an OpenAPI specification.

Swashbuckle.AspNetCore is more tightly integrated with ASP.NET Core, making it easier to use for .NET developers. However, openapi-generator offers greater flexibility and language support, making it suitable for a wider range of projects and use cases.

24,727

📘 OpenAPI/Swagger-generated API Reference Documentation

Pros of Redoc

  • Offers a more visually appealing and customizable documentation interface
  • Supports advanced features like authentication, callbacks, and discriminators
  • Provides better performance for large API specifications

Cons of Redoc

  • Requires separate generation and hosting of the documentation
  • Less integrated with ASP.NET Core ecosystem
  • May require more manual configuration and setup

Code Comparison

Swashbuckle.AspNetCore:

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

Redoc:

<!DOCTYPE html>
<html>
  <head>
    <title>API Documentation</title>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"></script>
  </head>
  <body>
    <redoc spec-url="http://petstore.swagger.io/v2/swagger.json"></redoc>
  </body>
</html>

Swashbuckle.AspNetCore is more tightly integrated with ASP.NET Core, offering easier setup and automatic API documentation generation. Redoc provides a more flexible and visually appealing documentation interface but requires separate hosting and manual configuration.

4,651

Turn any OpenAPI2/3 and Postman Collection file into an API server with mocking, transformations and validations.

Pros of Prism

  • Language-agnostic: Works with any API description format (OpenAPI, AsyncAPI, etc.)
  • Mock server capabilities: Can generate mock responses based on API specifications
  • CLI tool: Offers a command-line interface for easy integration into workflows

Cons of Prism

  • Less integrated with ASP.NET Core: Requires additional setup for .NET projects
  • Limited customization options for .NET-specific features
  • No built-in UI for API documentation (unlike Swashbuckle's Swagger UI integration)

Code Comparison

Swashbuckle.AspNetCore (in Startup.cs):

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

Prism (command-line usage):

prism mock api-specification.yaml

Summary

Prism is a versatile, language-agnostic tool for API mocking and testing, while Swashbuckle.AspNetCore is tailored specifically for ASP.NET Core applications. Prism offers broader compatibility and a powerful CLI, but lacks the tight integration and .NET-specific features provided by Swashbuckle. Choose Prism for cross-language projects or when mock server capabilities are crucial, and Swashbuckle for seamless integration with ASP.NET Core and built-in Swagger UI documentation.

7,118

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.

Pros of NSwag

  • Supports more platforms, including ASP.NET Core, ASP.NET Web API, and TypeScript
  • Offers client code generation for multiple languages (C#, TypeScript, JavaScript)
  • Provides a command-line interface for easier integration into build processes

Cons of NSwag

  • Less extensive documentation compared to Swashbuckle.AspNetCore
  • Smaller community and fewer third-party extensions
  • May require more configuration for complex scenarios

Code Comparison

Swashbuckle.AspNetCore:

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

NSwag:

services.AddSwaggerDocument(config =>
{
    config.PostProcess = document =>
    {
        document.Info.Version = "v1";
        document.Info.Title = "My API";
    };
});

Both libraries offer similar functionality for generating Swagger/OpenAPI documentation, but NSwag provides additional features for client code generation and supports a wider range of platforms. Swashbuckle.AspNetCore, on the other hand, has more extensive documentation and a larger community, which can be beneficial for troubleshooting and finding solutions to common issues.

Automated JSON API documentation for API's built with Spring

Pros of springfox

  • More mature project with a longer history and larger community
  • Supports a wider range of Spring Framework versions
  • Offers more customization options for API documentation

Cons of springfox

  • Less active development and slower release cycle
  • More complex configuration process
  • Limited support for newer Spring Boot versions

Code Comparison

Springfox configuration:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build();
    }
}

Swashbuckle.AspNetCore configuration:

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

Both libraries aim to generate Swagger/OpenAPI documentation for APIs, but they target different ecosystems. Springfox is designed for Java Spring applications, while Swashbuckle.AspNetCore is for .NET Core applications. Springfox offers more customization options but requires more configuration, whereas Swashbuckle.AspNetCore provides a simpler setup process with good integration into the ASP.NET Core pipeline.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Swashbuckle.AspNetCore

NuGet NuGet Downloads

Build status Code coverage OpenSSF Scorecard

Help Wanted

Swagger tooling for APIs built with ASP.NET Core.

Generate beautiful API documentation, including a UI to explore and test operations, directly from your application code.

In addition to its Swagger 2.0 and OpenAPI 3.0 generator, Swashbuckle also provides an embedded version of the awesome swagger-ui project that's powered by the generated Swagger JSON documents. This means you can complement your API with living documentation that's always in sync with the latest code. Best of all, it requires minimal coding and maintenance, allowing you to focus on building an awesome API.

But that's not all...

Once you have an API that can describe itself with a Swagger document, you've opened the treasure chest of Swagger-based tools including a client generator that can be targeted to a wide range of popular platforms. See swagger-codegen for more details.

Compatibility

Swashbuckle VersionASP.NET CoreSwagger/OpenAPI Spec.swagger-uiRedoc
CI>= 8.0.02.0, 3.05.x.x2.x.x
9.0.3>= 8.0.02.0, 3.05.26.22.5.0
8.1.4>= 8.0.0, 2.3.x2.0, 3.05.22.02.5.0
7.3.2>= 8.0.0, 6.0.x, 2.1.x2.0, 3.05.20.12.4.0
6.9.0>= 6.0.0, 2.1.x2.0, 3.05.17.142.1.5

Getting Started

  1. Install the kitchen-sink NuGet package into your ASP.NET Core application:

    dotnet add package Swashbuckle.AspNetCore
    
  2. Register the Swagger generator in your application's startup path, defining one or more Swagger documents. For example:

    using Microsoft.OpenApi.Models;
    
    services.AddMvc();
    
    services.AddSwaggerGen(options =>
    {
        options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
    });
    
  3. Ensure your API endpoints and any parameters are decorated with [Http*] and [From*] attributes, where appropriate.

    [HttpPost]
    public void CreateProduct([FromBody] Product product)
    {
        // Implementation goes here
    }
    
    [HttpGet]
    public IEnumerable<Product> SearchProducts([FromQuery]string keywords)
    {
        // Implementation goes here
    }
    

[!NOTE] If you omit the explicit parameter bindings, the generator will describe them as "query" parameters by default.

  1. Expose the Swagger/OpenAPI JSON document endpoint(s) using one of following methods:

    • Add endpoints if you're using endpoint-based routing:
    app.MapEndpoints(endpoints =>
    {
        // Your own endpoints go here, and then...
        endpoints.MapSwagger();
    });
    
    • Inserting the Swagger/OpenAPI middleware:
    app.UseSwagger();
    

    At this point, you can spin up your application and view the generated Swagger document at /swagger/v1/swagger.json.

  2. Optionally, insert the swagger-ui middleware if you want to expose interactive documentation, specifying the Swagger document(s) to power it from:

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

    Now you can restart your application and check out the auto-generated, interactive documentation at /swagger.

System.Text.Json (STJ) vs Newtonsoft.Json (Json.NET)

In versions of Swashbuckle.AspNetCore prior to 5.0.0, Swashbuckle would generate Schemas (descriptions of the data types exposed by an API) based on the behavior of the Newtonsoft.Json serializer. This made sense because that was the serializer that shipped with ASP.NET Core at the time. However, since ASP.NET Core 3.0, ASP.NET Core introduces a new serializer, System.Text.Json (STJ) out-of-the-box.

If you want to use Newtonsoft.Json instead, you need to install a separate package and explicitly opt-in. By default Swashbuckle.AspNetCore will assume you're using the System.Text.Json serializer and generate Schemas based on its behavior. If you're using Newtonsoft.Json then you'll need to install a separate Swashbuckle package, Swashbuckle.AspNetCore.Newtonsoft to explicitly opt-in.

Below is an example of how to do this for ASP.NET Core MVC:

dotnet add package Swashbuckle.AspNetCore.Newtonsoft
services.AddMvc();

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

services.AddSwaggerGenNewtonsoftSupport();

Swashbuckle, ApiExplorer, and Routing

Swashbuckle relies heavily on ApiExplorer, the API metadata layer that ships with ASP.NET Core. If you're using the AddMvc(...) helper methods to bootstrap the MVC stack, then API Explorer will be automatically registered and Swashbuckle will work without issue.

However, if you're using AddMvcCore(...) for a more paired-down MVC stack, you'll need to explicitly add the API Explorer services:

services.AddMvcCore()
        .AddApiExplorer();

Additionally, if you are using conventional routing (as opposed to attribute routing), any controllers and the actions on those controllers that use conventional routing will not be represented in API Explorer, which means Swashbuckle won't be able to find those controllers and generate Swagger operations from them.

For instance:

app.UseMvc(routes =>
{
   // SwaggerGen won't find controllers that are routed via this technique.
   routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});

You must use attribute routing for any controllers that you want represented in your Swagger document(s):

[Route("example")]
public class ExampleController : Controller
{
    [HttpGet("")]
    public IActionResult DoStuff() { /* Your implementation */ }
}

Refer to the ASP.NET Core MVC routing documentation for more information.

Components

Swashbuckle consists of multiple components that can be used together or individually depending on your needs.

At its core, there's a Swagger generator, middleware to expose Swagger (OpenAPI) documentation as JSON endpoints, and a packaged version of the swagger-ui. These three packages can be installed with the Swashbuckle.AspNetCore "metapackage" and will work together seamlessly (see Getting Started) to provide beautiful API documentation that is automatically generated from your code.

Additionally, there's add-on packages (CLI tools, an alternate UI using Redoc etc.) that you can optionally install and configure as needed.

"Core" Packages

PackageNuGetDescription
Swashbuckle.AspNetCore.SwaggerNuGetExposes Swagger JSON endpoints. It expects an implementation of ISwaggerProvider to be registered in the DI container, which it queries to retrieve OpenApiDocument instance(s) that are then exposed as serialized JSON.
Swashbuckle.AspNetCore.SwaggerGenNuGetInjects an implementation of ISwaggerProvider that can be used by the above component. This particular implementation generates OpenApiDocument instance(s) from your application endpoints (controllers, minimal endpoints etc.).
Swashbuckle.AspNetCore.SwaggerUINuGetExposes an embedded version of swagger-ui. You specify the API endpoints where it can obtain Swagger documents from, and it uses them to power interactive documentation for your API.

Additional Packages

PackageNuGetDescription
Swashbuckle.AspNetCore.AnnotationsNuGetIncludes a set of custom attributes that can be applied to controllers/endpoints, actions and models to enrich the generated documentation.
Swashbuckle.AspNetCore.CliNuGetProvides a command line interface (CLI) for retrieving OpenAPI documents directly from an application start-up assembly and then writing to a file.
Swashbuckle.AspNetCore.ReDocNuGetExposes an embedded version of the Redoc UI (an alternative to swagger-ui).

Community Packages

These packages are provided by the .NET open-source community.

PackageNuGetDescription
Swashbuckle.AspNetCore.FiltersNuGetSome useful Swashbuckle filters which add additional documentation, e.g. request and response examples, authorization information, etc. See its README for more details.
Unchase.Swashbuckle.AspNetCore.ExtensionsNuGetSome useful extensions (filters), which add additional documentation, e.g. hide PathItems for unaccepted roles, fix enumerations for client code generation, etc. See its README for more details.
MicroElements.Swashbuckle.FluentValidationNuGetUse FluentValidation rules instead of ComponentModel attributes to augment generated Swagger Schemas.
MMLib.SwaggerForOcelotNuGetAggregate documentations over microservices directly on Ocelot API Gateway.

Configuration and Customization

The steps described above will get you up and running with minimal set up. However, Swashbuckle offers a lot of flexibility to customize as you see fit.

Check out the table below for the full list of possible configuration options.

ComponentConfiguration and Customization
Swashbuckle.AspNetCore.SwaggerChange the Path for Swagger JSON Endpoints
Modify Swagger with Request Context
Serialize Swagger JSON in the 2.0 format
Working with Virtual Directories and Reverse Proxies
Customizing how the OpenAPI document is serialized
Swashbuckle.AspNetCore.SwaggerGenAssign Explicit OperationIds
List Operations Responses
Flag Required Parameters and Schema Properties
Handle Forms and File Uploads
Handle File Downloads
Include Descriptions from XML Comments
Provide Global API Metadata
Generate Multiple Swagger Documents
Omit Obsolete Operations and/or Schema Properties
Omit Arbitrary Operations
Customize Operation Tags (e.g. for UI Grouping)
Change Operation Sort Order (e.g. for UI Sorting)
Customize Schema Id's
Override Schema for Specific Types
Extend Generator with Operation, Schema & Document Filters
Add Security Definitions and Requirements
Add Security Definitions and Requirements for Bearer auth
Inheritance and Polymorphism
Swashbuckle.AspNetCore.SwaggerUIChange Relative Path to the UI
Change Document Title
Change CSS or JS Paths
List Multiple Swagger Documents
Apply swagger-ui Parameters
Inject Custom JavaScript
Inject Custom CSS
Customize index.html
Enable OAuth2.0 Flows
Use client-side request and response interceptors
Swashbuckle.AspNetCore.AnnotationsInstall and Enable Annotations
Enrich Operation Metadata
Enrich Response Metadata
Enrich Parameter Metadata
Enrich RequestBody Metadata
Enrich Schema Metadata
Apply Schema Filters to Specific Types
Add Tag Metadata
Swashbuckle.AspNetCore.CliRetrieve Swagger Directly from a Startup Assembly
Use the CLI Tool with a Custom Host Configuration
Swashbuckle.AspNetCore.ReDocChange Relative Path to the UI
Change Document Title
Apply Redoc Parameters
Inject Custom CSS
Customize index.html