How to: Create API documentation using OpenAPI & Swagger
How to: Create API documentation using OpenAPI & Swagger

Introduction

In this post, I show how to create API documentation using OpenAPI & Swagger. This post will help to cover a part of knowledge required to complete Azure AZ-203 certification.

To start with Azure AZ-203 certification, take a look at my post EXAM AZ-203: DEVELOPING SOLUTIONS FOR MICROSOFT AZURE

What is API documentation ?

API documentation is the information that is required to successfully consume and integrate with an API. This can be in the form of technical writing, code samples and examples for better understanding how to consume an API.

API Documentation using OpenAPI & Swagger

When consuming a Web API, understanding its various methods can be challenging for a developer who is new to consume our API.

Swagger, also known as OpenAPI, solves the problem of generating useful documentation and help pages for Web APIs.

In this post, Swashbuckle.AspNetCore is shown with a demo app.

Swashbuckle.AspNetCore is an open source project for generating Swagger documents for ASP.NET Core Web APIs.

Additional Resource For Swagger

Swagger

Background of Demo App

I created an demo App with N-Tier architecture that uses Azure SQL database as back end database. Demo app has a controller called Product which does CURD functionality.

The full demo application is available for free and you may download from my GitHub repository.

To download this demo related code, pick branch code "feature/ImplementCURDFunctionality"

Get Started

In this demo app, I will be using my existing asp.net core API app and add code to start showing API documentation using Swagger's OpenAPI

Setup and Configure OpenAPI & Swagger

Step 1

Install nuget package Swashbuckle.AspNetCore. and some minimum setup to start showing API documentation automatically.

Step 2

Add Swagger configuration to the ConfigureServices method from the Startup class.

services.AddSwaggerGen(
                options =>
                {
                    var assembly = typeof(Startup).Assembly;
                    var assemblyProduct = assembly.GetCustomAttribute().Product;

                    options.DescribeAllEnumsAsStrings();
                    options.DescribeAllParametersInCamelCase();
                    options.DescribeStringEnumsInCamelCase();

                    var info = new Info
                    {
                        Version = "v1",
                        Title = "KarthikTechBlog:Shopping - V1",
                        TermsOfService = "None",
                        Contact = new Contact()
                        {
                            Name = "Karthik",
                            Email = "karthiktechblog.com@gmail.com",
                            Url = "http://www.karthiktechblog.com"
                        }
                    };

                    options.SwaggerDoc("v1", info);

                    // Set the comments path for the Swagger JSON and UI.
                    var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                    var xmlPath = Path.Combine(basePath, "KarthikTechBlog.xml");
                    options.IncludeXmlComments(xmlPath);

                    options.CustomSchemaIds(x => x.FullName);
            }
            );

Step 3

Next is to add Swagger in the request pipeline.

// Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();

            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1");
            });

Step 4

Add required attributes to the controller action methods to show in API documentation. Adding ProducesResponseType attribute to the method help determines what is expected from API endpoint.

[HttpGet("")]
[ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ModelStateDictionary), StatusCodes.Status404NotFound)]
public async Task GetProducts()
{
	var products = await ProductService.GetProductsAsync();

	var model = Mapper.Map>(products);
	return new OkObjectResult(model);
}

To read more, visit how to implement create, read, update, and delete functionalities using Entity Framework Core

Create API documentation using OpenAPI & Swagger
Create API documentation using OpenAPI & Swagger

Conclusion

In this post, I showed how to create API documentation using OpenAPI & Swagger. This post is part of learning track for azure AZ-203 certification.

That’s all from this post. If you have any questions or just want to chat with me, feel free to leave a comment below.

Leave a Reply

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

Verified by MonsterInsights