Implement Swagger In ASP.net Core Web API


  In this article we are just going to implement the Swagger UI for the Web API which works similar to the Postman. In simple words, we can say it is a tool which describes our API structure and functionality to call our API directly from the UI.

Swagger defines a set of rules and tools to semantically define APIs. It can be called as a framework for describing your APIs in a standard common language that everyone can understand.

What is Swagger?

The Swagger is a set of rules which provides the users functionality to understand the structure of the REST API, and it can also be used to share documentation among product managers, testers, and developers, but can also be used by various tools to automate API related processes.

There are many such frameworks around but Swagger comes with many benefits.

  • Swagger is understandable by technical as well as non-technical users. Because of its friendly UI, it can be understandable by project managers, BA’s, & even the clients.
  • Testing and debugging APIs gets easier.
  • Readable by both human and machine, you can easily use it to automate the API process.

APIs that use Swagger are easy to understand, modify, and consume. Everything gets clear and that is the reason why big companies are using it in their processes.

Testing Web API’s is a challenge. It has a dependency on various third-party tools, requires installing different packages,  and it can get all messed up. Swagger can make it easy and quick.

Implement Swagger


Step 1 - Open the Visual Studio 2019 and Select the Project Type Asp.net Core Web App MVC template , and click on next.




Step 2 - give the title of the Project and then Click on the Next.
Step 3 - Now in this step Select your framework, I am using the framework (.net core 3.1) and Click on Create


Now, we are going to add a package where you can use the NuGet Package Manager or Package Manage Console. 

  • For Package Manager, just go to Tools→ NuGet Package Manager → NuGet Package Manager 
  • or you can right click on Dependencies and select nuget package manager
    • in browse tab, search Swashbuckle. AspNetCore and install it.


After clicking on the installation you will get the two pop-up dialogue, in this dialogue click on install and I Accept.

  • For Package Manager Console, go to Tools → NuGet Package Manager → Package Manager Console
    • in console, add the following command and execute it 
Install-Package Swashbuckle.AspNetCore 



Now, once the Installation is done, and If you try to run the code and go to HTTP:localhost:[port number]/swagger/index.html then it will show you output similar to below:

So, what it means is we have installed the packages but not implemented till now.

So, go to the Startup.cs file.

Add the following code to the ConfigureServices Method.

services.AddSwaggerGen(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo{ Version = "v1", Title = "Implement Swagger UI", Description = "A dotnet Office example to Implement Swagger UI", }); });





Add the following code to the Configure Method of the Startup.cs file.

app.UseSwagger(); app.UseSwaggerUI(c =>{ c.SwaggerEndpoint("/swagger/v1/swagger.json", "Showing API V1"); })



Now if you can check you will get an output like the following image, but we will not get any controller or any Methods information or structure information below that we will get just the Swagger Project Name and the Description as below : 


Now, in Swagger if we want to show some information of contact and license and some link then you can as below :

 services.AddSwaggerGen();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Implement Swagger UI",
                    Description = "A dotnet Office example to Implement Swagger UI",
                    TermsOfService = new Uri("https://dotnetoffice.com/"),
                    Contact = new OpenApiContact
                    {
                        Name = "DotNet Office",
                        Email = "Email Address",
                        Url = new Uri("https://www.youtube.com/thedotnetoffice"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "License Information",
                        Url = new Uri("https://www.youtube.com/thedotnetoffice"),
                    }
                });
            });

In the output of the above code, you will get something like the following image.

Now add a method in Home controller class called DotNetOffice_Swagger like below
 
 [Route("DotNetOffice_Swagger")]     
      
        public async Task<string> DotNetOffice_Swagger()
        {
            return "The Dot Net office";
        }



Now Run your application and redirect to HTTP:localhost:[port number]/swagger/index.html 
you will see below error 

So, What this Error means is we have done something wrong or there is a missing method of the controller which could be an HTTP GET or HTTP POST, or we have added the Service or new controller,We have to add the HTTP verbs in Action method like below

 [Route("DotNetOffice_Swagger")]     
        [HttpGet]
        public async Task<string> DotNetOffice_Swagger()
        {
            return "The Dot Net office";
        }



Now Run your application and redirect to HTTP:localhost:[port number]/swagger/index.html 


Here you can see , the API action method name , expand this action method and click on "Try it out" and execute the API method.
You will see the out[ut result as  The Dot Net office




Now This is the way , we can test our API method using the Swagger , without installing third party tool like , Postman or other tools.

Share this

Related Posts

Previous
Next Post »