Web API Documentation Using Swagger in .Net Core


Swagger1

Documentation by listening this word developer gets irritated. Developers needs more focus on logic and implementation of code and get very less time to document the things. As we are in IT we always hear POSTMAN tool to test API request and response. For this we need to share the endpoint and parameters for an API to the teams and we need to document it request response everything.

This is hectic, to make it easy we have swagger which is open source API documentation NuGet package.

What is Swagger(Open API)?

Swagger is open source API documentation package available in NuGet Package.

It allows user to understand the capabilities of REST API without directly accessing the  source code.

Open API:

Open API is a specification is documentation that explains the capability of an API .

 Swagger UI:

 is used to show the UI.

In this blog I will explain how to create .NET Core Web API and add Swagger package and its customizations.

1. Create .NET Core Application for API

2. Add Swashbuckle.AspNetCore Package and installation

3. Add and Configure Swagger middleware 

4.Customize and extend

5. XML Comments

1. Create .NET Core Application for API:

Open Visual Studio 2017 or 2019
go to File -> New -> Project
swagger2

Select ASP.NET Core Web Application

Swagger3

Select API  and click OK
Swagger5

We have successfully created API.
Swagger6


2. Add Swashbuckle.AspNetCore Package and installation:

Go to  Tools-> NuGet Package Manager -> Manage NuGet Packages for Solution
Swager7

Search for Swashbuckle.AspNetCore and install

swagger9

Swager11

3. Add and Configure Swagger middleware :

in Configuration Services Add below service.

services.AddSwaggerGen();
Swagger13

Configure Middleware:

Add below code to Configure method.
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 First Swagger API V1");
            });
swagger18


Run the Project and go to
 localhost:port/swagger/index.html
swagger19

Now Swagger Documentation ready.
We can send request to endpoint by selecting one and clicking execute.
swagger21
for put and post methods we can pass FromBody (Request Body) and parameters from this UI and get response from here only.
swagger151


4.Customize and extend:

Their are so many customizations available I will explain some of them
Configure to Base URL:

 To make swagger to come in base URL. Add RoutePrefix

app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My First Swagger API V1");
                c.RoutePrefix = string.Empty;
            });

Swagger UI will come in base URL
Swagger24
Add Owner name and terms and conditions to your UI:

a. add this in startup class
using Microsoft.OpenApi.Models;
b. Update SwaggerGen in ConfigureServices to below.

services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Swagger API",
                    Description = "A simple example ASP.NET Core Web API for Swagger",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "Contact",
                        Email = string.Empty,
                        Url = new Uri("https://example.com/contact"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri("https://example.com/license"),
                    }
                });
            });

After run and see in browser.

Swagger25


5. XML Comments

We Can enable XML comments to Swagger UI to Give more information to API documentation.

Go to Project Properties and build tab enable xml documentation file checkbox.
Swagger24



Add below Code in SwaggerGen:

 services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version = "v1",
                    Title = "Swagger API",
                    Description = "A simple example ASP.NET Core Web API for Swagger",
                    TermsOfService = new Uri("https://example.com/terms"),
                    Contact = new OpenApiContact
                    {
                        Name = "Contact",
                        Email = string.Empty,
                        Url = new Uri("https://example.com/contact"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "Use under LICX",
                        Url = new Uri("https://example.com/license"),
                    }
                });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
Swager30

Adding XML Comments :
 /// <summary>
        /// Get Method to Get all Values
        /// </summary>
        /// <remarks>
        /// Sample request:
        ///
        ///     POST /Todo
        ///     {
        ///        "id": 1,
        ///        "name": "Item1",
        ///        "isComplete": true
        ///     }
        ///
        /// </remarks>
        /// <param name="item"></param>
        /// <returns>A newly created TodoItem</returns>
        /// <response code="201">Returns the newly created item</response>
        /// <response code="400">If the item is null</response>       

Swagger34



Swagger42



By using this we don't need to create documentation for each API with endpoint Parameters and everything.

Thanks for Reading.



Read my blogs below.



Post a Comment

0 Comments