Getting Started with Swagger in ASP.NET Core Web API

  • Post core / Swagger
  • Reading time:3 mins read

Swagger is describing RESTful APIs manifested using JSON  like PostmanPostman is the world’s leading  API platform but in some cases Swagger is more powerful than Postman. Swagger UI is wonderfully documented so that it can be shared among product managers, testers and developers.

STEP 1 :

Create an ASP.NET Core Web API project. I am using VS 19 and my Target Framework is .Net 5.0.

STEP 2 :

Now expand the project and go to Dependencies –> Packages . Here you can see a package already installed named “Swashbuckle.AspNetCore”

If you cant see the packages there please go to NuGet Package Manager and install the package.

STEP 3 :

Now Open the Startup.cs file.  In the namespace you can see “using Microsoft.OpenApi.Models;”  This namespace is used for Swashbuckle.AspNetCore packages.  Add it if it is not exist in your solution.

using Microsoft.OpenApi.Models;

STEP 4 :

Go to ConfigureServices(IServiceCollection services) method in Startup.cs file.

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

Here, services.AddSwaggerGen method is using for Swagger UI

STEP 5 :

Now go to the Configure(IApplicationBuilder app, IWebHostEnvironment env) method in the same file.


app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerDemo v1"));
  • app.UseSwagger() method is using to serve the JSON endpoints and it holds the API Metadata
  • app.UseSwaggerUI() method is using to serve the UI for the API.

In Visual Studio 2019 Swagger UI  will create automatically with ASP.NET Core Web API project . If not then simply follow this steps to add SwaggerUI in your project.


URL : https://localhost:*****/swagger/index.html

Expand the /WeatherForecast Get API. Click Try it out button. This will show you the list data of  WeatherForecast which controller is created by VS during project creation.

That’s All.


Leave a Reply