Friday, 10 April 2020

ASP.NET CORE : Version specific swagger document for Web Api Core [ using asp.net core 3.0 ]


Objective : We have versioned our Web APi and want to create swagger /OpenAPI documentation version specific. i.e. when user will select specific version he would be able to see api specific to selected version.

Versioning for API is easy using ASP.NET core's inbuilt middle ware. I have created a separate post related to API versioning. This post is specific to creation of version specific swagger document.

Nuget Packages : below are the list of Nuget packages needed to implement versioning and Swagger documentation in the application.

Microsoft.AspNetCore.Mvc.Version : To implement versioning.

Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer: Used by swagger to generate version specific document.

Swashbuckle.AspNetCore.Swagger : Swagger middleware exposes json endpoint.

Swashbuckle.AspNetCore.SwaggerGen : Generates JSON file

Swashbuckle.AspNetCore.SwaggerUI : Generates interactive UI documentation for API.

Now, we will see code which we have to add in ConfigureServices and Configure methods:

Need  to add below services to implement inbuilt versioning functionality:

            services.AddApiVersioning(o =>
            {
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = new ApiVersion(1, 0);
            });   // inbuilt versioning implementation

            services.AddVersionedApiExplorer(); // swagger versioning specific

// above code is required to implement versioning. below code is required for swagger documentation.

services.AddSwaggerGen(
    options =>
    {
                    
        var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
        // add a swagger document for each discovered API version
        foreach (var description in provider.ApiVersionDescriptions)
        {
            options.SwaggerDoc(description.GroupName, new OpenApiInfo { Version = description.ApiVersion.ToString(),
                                                                        Description ="Sample API version: "+ description.GroupName ,
                                                                        Title="API Versioning Sample"
                                                                      });
        }
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        Console.WriteLine("***************************** " + xmlPath);
        options.IncludeXmlComments(xmlPath);
    });

We need to add below code in Configure method to enable swagger documentation :

  app.UseSwagger();
            app.UseSwaggerUI(
                options =>
                {
                    var provider = app.ApplicationServices.GetRequiredService<IApiVersionDescriptionProvider>();
                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        options.SwaggerEndpoint( $"/swagger/{description.GroupName}/swagger.json",description.GroupName.ToUpperInvariant());
                    }
                });

Now we have to add APIVersion Attribute on Controller /Action methods. like :

    /// <summary>
    /// this is sample api for version 1.0
    /// </summary>
    [ApiVersion("1.0")]
    [ApiController]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class EmployeeController : ControllerBase
    {
        /// <summary>
        /// Get api for version 1.0
        /// </summary>
        [HttpGet]
        public IActionResult Get()
        {
            return Ok(" Hello from v1");
        }
    }
 
    /// <summary>
    /// this is sample api for version 2.0
    /// </summary>
    [ApiVersion("2.0")]
    [ApiController]
    [Route("api/v{version:apiVersion}/[controller]")]
    public class Employee2Controller : ControllerBase
    { /// <summary>
      /// Get api for version 2.0
      /// </summary>
      ///
      [HttpGet]
        public IActionResult Get()
        {
            return Ok(" Hello from v2");
        }
    }

[Copy paste above code  in editor for better readability/understanding]

Some important point to remember:

1. Make sure that each action method is decorated with proper get/post attribute.
2. Route is specified for each action method.
3. Xml comments are added for each action method.
4. Go to project Properties->build->check-Xml document file. ( if you are using xml comments in swagger)




Resource :
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/blob/master/README.md#list-multiple-swagger-documents

No comments:

Post a Comment

How to create and use middleware in asp.net core

Middleware is piece of code that's assembled into an app pipeline to handle requests and responses.  Each middleware component in the re...