Swagger ASPNET Core 6 Open APi

Today in this article, we shall see how to add Swagger API Documentation in ASP.NET Core-based API application using OpenAPI V3 specification.

Swagger or OpenAPI describes the standards and specifications for the RESTFul API description.

These specifications are an attempt to create a universal and language-agnostic description for describing the REST API.

In this article, we shall see below the overall aspects,

ASP.NET Core 3.1 uses OpenAPI V3.0 specifications which are more generic guidelines and specifications around how the API documentation should be.

So let’s get started…

Create ASP.NET Core API

Create ASP.NET .NET 6 API

Add Swagger API Documentation

Add Swashbuckle.AspNetCore NuGet package

Please add the below Nuget package to your WebAPI using a Command prompt or PMC(package manager console)

PM> Install-Package Swashbuckle.AspNetCore -Version <version>

Note: Your package might be in preview mode. Please update the version to the latest once it is available.

This NuGet package shall add all other required components as shown below and you need not have to add them explicitly,

  • Swashbuckle.AspNetCore.SwaggerUI
  • Swashbuckle.AspNetCore.Swagger
  • Swashbuckle.AspNetCore.SwaggerGen

Update the ConfigureServices() method as below,

Add the below line to the ConfigureServices() method as shown below,

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

Please add the below namespace to use class ‘OpenApiInfo’,

using Microsoft.OpenApi.Models;

Please make a note of the differences between the .NET Core 2.xx version and the 3.0 + version,


Update Configure() method

Add below lin UseSwagger and UseSwaggerUI to Configure() method enabling API pipeline with Swagger capability as shown below,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Let’s execute the swagger URL,

Add Swagger NET5

Enabling XML documentation

Let’s enable API/method level documentation to our API/Service. Please update the project(.csproj) file as below. The XML file gets created in the output folder itself.

  <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>

The above setting will generate the required method-level documentation in the form of an XML file in the project root directory.

Please update the Configure method as below to read this XML file.


Update to Configure method for XML document generation

The updated method as below,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title ="MyTestService", Version = "v1", });
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);

            });
        }

The above setting will generate documentation at each method level as below,

Add Swagger API Documentation

The swagger JSON file can be accessed locally via the below route.

https://localhost:44320/swagger/v1/swagger.json
blank

That’s all!

Happy coding !!

References:

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

It’s simple to enable Swagger Open API documentation in the .NET Core API using the Swashbuckle NuGet package. Good API documentation helps reduce dependencies between different teams working on API.

Once enabled swagger provides the advantage of understanding the REST API(for developers ) consuming Web API. It provides easy ready API documentation and details of the capabilities a service and hence an organization owns.




Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



9 thoughts on “Add Swagger API Documentation in ASP.NET Core

  1. Thanks have worked with some other additional configuration on csproj. But I don’t know if that is something related to that or not the identity jumped in 1000th continued to count after id 3 like1004.

Leave a Reply

Your email address will not be published. Required fields are marked *