Swagger API in ASP.NET Core Web API

How to Install Swagger API in ASP.NET Core Web API

In this article, I will discuss How to Install and Use Swagger API in the ASP.NET Core Web API Project. I will show you both the Options, i.e., Adding Swagger API while creating the Project and Adding Swagger API after creating the Project. Please read our previous article, where we discussed Default ASP.NET Core Web API Files and Folders, i.e., those created by default when we create a new ASP.NET Core Web API Application.

Swagger in ASP.NET Core Web API

Swagger is a powerful tool for documenting and consuming RESTful web services. It provides a user-friendly interface to interact with the API, test its endpoints directly through the browser, and understand its capabilities. Using Swagger in ASP.NET Core Web API typically involves integrating the Swashbuckle library, which is a .NET implementation of Swagger. Remember to properly secure and restrict access to Swagger endpoints and documentation in a production environment.

Testing ASP.NET Core Web API Project with Swagger

Now let’s move on to testing the ASP.NET Core Web API Project with Swagger:

  • Install Swagger UI: If you haven’t already installed Swagger UI in your ASP.NET Core Web API project, please install it. Swagger UI provides a user-friendly interface to explore and interact with your API documentation. 
  • Launch your Web API Project: Start your ASP.NET Core Web API project and navigate to the Swagger UI endpoint. This endpoint is usually available at /swagger or /swagger/index.html.
  • Explore the API Documentation: In Swagger UI, you will see a list of available endpoints grouped by tags or categories. Click on an endpoint to expand it and view the available operations (GET, POST, PUT, DELETE, etc.). Click on an operation to see the request details, including parameters, request body, and response structures.
  • Execute Requests: To test your API, click on an operation in Swagger UI. It will display an interface to enter the required parameters and payload (if applicable). Fill in the necessary details and click the “Try it out” button.
  • View the Response: Swagger UI will send the request to the specified URL with the provided parameters. It will display the response received from the API, including the status code, response headers, and the response body.
Install the Swagger Package in ASP.NET Core Web API:

Open the NuGet Package Manager in Visual Studio or use the dotnet CLI to install the Swashbuckle.AspNetCore package. It is possible to install the Swagger API while creating a new Project. Let us proceed and see all the available options to install the Swagger API Package.

Method 1: Enable Swagger API While Creating the ASP.NET Core Web API Project

While creating a new ASP.NET Core Web API Project, we can check the Enable OpenAPI support checkbox while providing the Additional Information, which will automatically install the Swagger API in our project, as shown in the image below.

Enable Swagger API While Creating the ASP.NET Core Web API Project

If you remember, in our Creating ASP.NET Core Web API Project in Visual Studio article, we checked this checkbox while creating the project, which is why we can access the Swagger Page in our application. If Swagger is installed, then you will find the corresponding Swashbuckle.AspNetCore package is inside the Packages folder, which comes inside the Dependencies folder, as shown in the image below. Any package that we install in our Project will come inside the Packages folder.

Enable Swagger API While Creating the ASP.NET Core Web API Project

Method 2: Installing Swagger API using NuGet Package Manager

You can install the Swagger API using NuGet Package Manager if you have already created the ASP.NET Core Web API Project without checking the Enable OpenAPI support checkbox. So, let us create a new ASP.NET Core Web API project with the name SwaggerDemo, and in the Addition Information window, please uncheck the Enable OpenAPI support checkbox as shown in the image below.

Installing Swagger API using NuGet Package Manager

Once you created the project, you can now see the Swashbuckle.AspNetCore package is not installed, as shown in the image below. Here, you can see no Packages folder under the Dependencies folder, which means no additional packages are installed in our project.

Installing Swagger API using NuGet Package Manager

Let us see how to add the Swagger Packages to our Project. To Add Swagger, open the NuGet Package Manager window and then search for Swashbuckle.AspNetCore is in the browse tab, as shown in the image below. Then, choose the Swashbuckle.AspNetCore package, select the project where you want to install this package, and finally, click on the Install button, as shown in the image below.

Installing Swagger API using NuGet Package Manager

Once you click on the Install button, it will open the Preview Changes window. Click on the OK button as shown in the below image.

Installing Swagger API in ASP.NET Core Web API using NuGet Package Manager

Then it will open the Accept License window, Accept the License by clicking on the I Accept button as shown in the below image.

Installing Swagger API in ASP.NET Core Web API using NuGet Package Manager

That’s it. It will install the Swagger API Package. If you verify the Dependencies folder, you will see the following. It should add the Packages folder, and within the Packages folder, it should add the Swashbuckle.AspNetCore package.

Installing Swagger API in ASP.NET Core Web API using NuGet Package Manager

Configure Swagger Services:

To configure Swagger API, we need to add the AddEndpointsApiExplorer() and AddSwaggerGen() services to the built-in dependency injection container within the Main method of the Program class, as shown in the code below.

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

Here,

  • AddEndpointsApiExplorer: The AddEndpointsApiExplorer() service enables API Explorer services required for generating the OpenAPI specification. This method adds services necessary for discovering endpoint metadata. This metadata is essential for tools like Swagger to generate accurate and useful documentation for your Web API.
  • AddSwaggerGen: The AddSwaggerGen() service is used for generating Swagger documents, which describe the structure and capabilities of your Web API. This method allows for customization of the Swagger documentation, such as setting the title and version and even adding custom descriptions and schemas.
Enable Swagger Middleware Components:

Once we configure the Swagger API services to the built-in dependency injection container, then we need to register the Swagger Middleware components to the Application Request Processing Pipeline. To enable Swagger Middleware, add the following within the Main method of the Program class.

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

Here,

  • UseSwagger(): The UseSwagger middleware generates and serves the Swagger JSON document. This document represents your API with all its endpoints, parameters, responses, etc., in a format that Swagger UI can interpret. This middleware is usually configured to be active only in development environments for security reasons, as publicly exposing API metadata can be a security risk. This middleware serves the generated Swagger JSON document at a specified URL (by default, /swagger/v1/swagger.json).
  • UseSwaggerUI(): The UseSwaggerUI middleware serves the Swagger UI, which is a web-based UI that provides information about the service’s endpoints and their parameters and allows for easy testing of these endpoints directly from the browser. Like UseSwagger, it is commonly enabled only in development environments.

With the above changes, the Program.cs class file code should look as follows:

namespace SwaggerDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllers();

            //Registering Swagger API Services
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();

            // Configure the HTTP request pipeline.

            //Registering Swagger Middlware Components
            if(app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }
            
            app.UseHttpsRedirection();
            app.UseAuthorization();
            app.MapControllers();
            app.Run();
        }
    }
}
Run the API:

Now, we need to Build and Run the project. Then, access the Swagger UI by navigating to the URL: http://localhost:<port>/swagger, as shown in the below image.

Run the API

Explore the API:
  • Swagger UI will display a user-friendly interface with a list of available API endpoints.
  • Click on an endpoint to expand it and view details like request parameters, response schemas, and example requests/responses.
  • You can use the provided interface to send requests and receive responses directly from Swagger UI.

The swagger will display the details of all the Web APIs available in your project. As you can see in the below image, it shows one API, i.e., /WeatherForecast, and the type is Get. Now click on the /WeatherForecast API to see the details shown in the image below.

Explore the API

Once you click on the /WeatherForecast API, it will show you the API details, as shown in the image below.

How to Install Swagger API in ASP.NET Core Web API

Testing the API:

Now let us see how to test the API, i.e., WeatherForecast API, using swagger. To test the API using Swagger, click the try it out button, as shown in the image below.

Testing the API

Once you click on the Try it Out button, it will open below the screen, and here, you need to click on the Execute button, as shown in the image below.

Testing the API

Once you click on the Execute button, it will send a request to the server, and then whatever response it receives from the server will display, as shown in the image below. Here, you can find the request URL, the response body, the response status code, and the response headers.

Swagger API in ASP.NET Core Web API

Customizing Swagger in .NET 8

Customizing Swagger in .NET 8 allows you to customize the Swagger UI and the generated OpenAPI specification to suit your project’s needs better. This can include custom information, such as API descriptions and contact information, licenses, versions, etc.

You can customize the Swagger metadata by configuring the SwaggerGen options in Program.cs. So, modify the AddSwaggerGen service as follows. As you can see here, we have provided more information about our APIs, like the Title, Version, Description, TermsOfService, Contact, and License.

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("V10", new OpenApiInfo
    {
        Title = "My Custom API",
        Version = "V10",
        Description = "A Brief Description of My APIs",
        TermsOfService = new Uri("https://dotnettutorials.net/privacy-policy/"),
        Contact = new OpenApiContact
        {
            Name = "Support",
            Email = "support@dotnettutorials.net",
            Url = new Uri("https://dotnettutorials.net/contact/")
        },
        License = new OpenApiLicense
        {
            Name = "Use Under XYZ",
            Url = new Uri("https://dotnettutorials.net/about-us/")
        }
    });
});

By default, Swagger API looks for Version V1, but we have changed the version to V10 here. So, we also need to configure the same into the Request Processing Pipeline. So, next, modify the UseSwaggerUI as follows:

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

With the above changes in place, run the application and navigate to the Swagger Page, and you should see the following:

Swagger API in ASP.NET Core Web API

That’s a brief overview of exploring an ASP.NET Core Web API project and integrating Swagger API documentation. In the next article, I will discuss Controllers in ASP.NET Core Web API Application. In this article, I try to explain the Swagger API in ASP.NET Core Web API. I hope you enjoy this Swagger API in the ASP.NET Core Web API article.

Leave a Reply

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