Document and Publish your ASP.NET Core API with Swagger (OpenAPI Specification)

Let me write an Agile story for this article and, excuse me, if my story isn’t following true agile standard. As a Developer, I want to expose (publish) ASP.NET Core API hosted in Azure Kubernetes Cluster to Internet Clients via Azure API Gateway. API application has already been built but it does not expose/publish any definition (schema) which is required by Azure API Gateway.

Welcome to Swashbuckle, the OpenAPI Specification for .NET, to document ASP.Net Core API application and to expose the schema required by Azure API Gateway in no time! The figure below shows API published to Azure API Gateway using OpenAPI Specification and how-to steps would follow-

Here are the steps needed to implement Swagger in ASP.NET Core API application:

(1) Add Swashbuckle.AspNetCore nuget package to ASP.NET Core project. There are three components in Swashbuckle.AspNetCore but they all are included in the package.

(2) Update the ConfigureServices method of Startup class to register Swagger. I am using the following code snippet in my project but you can find more details at – Get started with Swashbuckle and ASP.NET Core.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
  c.SwaggerDoc("v1", new Info
  {
     Version = "v1",
     Title = "GDT Demo API",
     Description = "Demo of ASP.NET Core Web API",
     TermsOfService = "https://swagger.io/license/",
     Contact = new Contact
     {
        Name = "GDT Cloud Team",
        Email = "cloudteam@gdt.com",
        Url = "https://www.gdt.com"
     }
  });
});

(3) Update Configure method of Startup class to use Swagger.

1
2
3
4
5
6
7
8
9
// Enable middleware to serve generated Swagger as a JSON endpoint.
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", "GDT Demo API V1");
});

(4) Build and Run the ASP.NET Core project in Visual Studio or your choice of code editor. You are good to go!

(5) Access Swagger UI in browser: http://your-app:port/swagger and make sure it works locally before publishing to Azure (or to your target environment).

Let’s see how Swagger UI looks at the internal load balancer of an API app deployed in Azure Kubernetes Service.

(6) Login to Azure Portal and Add an API using swagger schema. Example: http://your-load-balance-ip-or-dns/swagger/v1/swagger.json

Conclusion

There are lot of complexities in securely publishing API application at Azure API Gateway from private network (vNET) in cloud or from an on-premise datacenter. GDT can help you in the Discovery/Assessments, Planning, Implementation and Monitoring of your cloud resources. Contact GDT’s Cloud Experts at cloudteam@gdt.com. They would love to hear from you.

 

 

Leave a Reply