Tuesday, June 2, 2020

Implementation of Swagger in webapi core 2.1

 Swagger Implementation:


  • Create an Asp.Net Core 2.1 web api project and install Swashbuckle.AspNet core(5.0.0) nuget package.
  • Swashbuckle comprises of 3 packages - A swagger generator, middleware to expose the generated  swagger as Json end points and middle ware to expose swagger-UI.
  • They can be installed togather via Swashbuckle.AspNet core(5.0.0) meta package: Like:                                                                                                                                                           PM > Install-Package Swashbuckle.AspNetCore
  • In Asp.net core 2.1, open Startup.cs file to add swagger service to middleware. Like:     
public void ConfigureServices(IServiceCollection services)
{

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Example API",
Description = "Example API", }); });
}

  • And enable the Swagger ui in configure() method: Like
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    app.UseMvc();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Example API");
    });
    }


This is all required to set up swagger. The one last thing to do change is, change in the application launch url, so that the swagger UI loads on launching. To set swagger UI as launch url, following steps to be as follows...

              1. Right click on the Asp. net core web application.
              2. And then click on properties.
              3. Navigate to debug tab.        
              4. On debug tab change Launch Browser value to "Swagger".
  • Now run the application, now you should see the swagger UI like this:

       

            
  • Swagger uses different colors for each HTTP verb to differentiate Api actions. Clicking on any method will give you details about the accepted parameters, return type and allows you to test         

 Swagger Versioning:
  • In Asp.Net core 2.1 web api project, install Microsoft.AspNetCore.MVC.Versioning(2.1.0) nuget package.
  • Then open Startup.cs file in your project, and then add the following code in Startup.cs file

  • And then open the controllers in your application, add below lines of code in route level.

  • Now run the application, you should see the versioning in swagger UI as follows:

Note: In our application, we use swagger versioning as one, here you can use versioning as per your requirement.




         




                                                                                                                                                                

1 comment: