December 11, 2019

Setup Swagger with .Net Core Web API

Swagger is a open-source framework for describing your API using a common language that everyone can understand, usually in json or yaml formats which could be readable for both humans and machines. Swagger makes it easire for developers to design, build, document, and consume RESTful web services.

It provides the following benefits:

  • Human and machine readable.
  • Easier to understand for less technnical people. Developers and non-developers i.e. product managers and even potential clients can have a better perspective of the design of your API.
  • Adoptable for new changes, because it reflects the changes immediately on your swagger UI without writing special code for swagger. You only make changes to your REST API and swagger will do its part on its own.

Here is how you can implement swagger in .Net Core API project.

  • First you have to install two Nuget paackages.

    • Swashbuckle.AspNetCore
    • Swashbuckle.AspNetCore.Annotations
  • Once you have installed Nuget Packages, then inside ConfigureServices() method in Startup.cs, add this section:

     services.AddSwaggerGen(c =>
     {
      c.OperationFilter();
      c.EnableAnnotations();
      c.SwaggerDoc("v1", new Info
      {
       Title = "My API",
       Version = "v1"
      });
     });
      
  • Inside Configure() method in Startup.cs, we have to tell IApplicationBuilder object to use Swagger:

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

When you run the .Net Core API project, go to the link, adding /swagger/index.html for your base URL. For example:

https://localhost:44319/swagger/index.html

It will display the swagger UI page similar to this.

No comments:

Post a Comment