Adding swagger through VSCode

Avishek Patra
2 min readFeb 18, 2018

In the last couple of days, I was checking a few developers are facing some issues while adding swagger to their web API’s when they are creating it from the VS Code environment. But this is also as straightforward as Visual Studio.

Today I’ll be taking you through the steps through which we can add swagger in our Web API

Let’s Open the .NET CLI or console and write the following command

dotnet new webapi

This will create a web API project without swagger added.

Directory Structure will look something like below

Step 1: Add NuGet Package

Open .NET Core CLI or console and run the following command

dotnet add TodoApi.csproj package Swashbuckle.AspNetCore

Step 2: Add & Configure Swagger to Middleware

Now we have to modify the ConfigureServices Method

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

Now add using Swashbuckle.AspNetCore.Swagger; so that compiler could know from the where the reference of Info class should be taken.

Step 3: Letting the middleware know about the swagger UI and the endpoint information

Navigate to the configure method of Startup.cs and add the following code

app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

As we are done, we have to run the application using the following command:

we can now open the swagger JSON like this

http://localhost:<some-port-number>/swagger/v1/swagger.json

And swagger UI can be opened using the following URL

http://localhost:<some-port-number>/swagger/

The swagger UI will look like something like in the browser:

Hope this will help.

You can download the code from the following repository in Github

If you liked this video then please like and share the post.

Originally published at http://coderera.wordpress.com on February 18, 2018.

--

--