Introduction to Swagger

Swagger is an open-source software framework backed by a large ecosystem of tools that helps developers design, build, document, and consume RESTful Web services. While most users identify Swagger by the Swagger UI tool, the Swagger toolset includes support for automated documentation, code generation, and test-case generation.

Swagger to ASP.NET Core Web API

Step1

Create a ASP.NET Core WEB API project.

swagger1

Step2

Select API version.

swagger2

Step3

Install Swashbuckle.AspNetCore nuget package , three packages –

  • a Swagger generator,
  • middleware to expose the generated Swagger as JSON endpoints
  • middleware to expose a swagger-ui that’s powered by those endpoints.

They can be installed together, via the Swashbuckle.AspNetCore meta-package.

PM > Install-Package Swashbuckle.AspNetCore

Step4

Open Startup.cs file to add swagger service to middleware.
public void ConfigureServices(IServiceCollection services)
{
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      services.AddSwaggerGen(c =>
      {
         c.SwaggerDoc("v1", new Info
         {
             Version = "v1",
             Title = "My API",
             Description = "My First ASP.NET Core Web API",
             TermsOfService = "None",
             Contact = new Contact()
             {
                 Name = "Keshab",
                 Email = "kesavnayak@techbloginterview.com",
                 Url = "www.techbloginterview.com" 
             }
        });
    });
}

Step5

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     else
     {
         app.UseHsts();
     }

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

Step6

https://localhost:44348/swagger/index.html
swagger3

Step7

Test the Swagger.

swagger4

Leave a Reply

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