TechBubbles Microsoft Technology BLOG

Using Swagger in ASP.NET Core 2.2

ASP.NET Core 2.2 introduces some new cool features to support Swagger in web API project. This post outlines the new core 2.2 features API Conventions and API Analyzers . Download ASP.NET Core 2.2 to test this feature.

The code described in this post can be downloaded from here

What is swagger?

Swagger also known as Open API is a specification for describing REST APIs. It helps your web api clients in consuming and testing. example: what the API method does and return?

How to use it?

Create a new web api project in ASP.NET CORE 2.2

Create

Install  NSwag.AspNetCore Nuget package for Swagger. Add following lines in Startup.cs file. More about NSwag can be read from here.

image

image

Run the application and hit Swagger end-point then you see the following screen

image

It describes your application and endpoints and models in your API. You can test Get method by clicking try out and hit execute button

image

In order to generate document for your API methods from code, you need to install Nuget package Microsoft.AspNetCore.Mvc.Api.Analyzers. This package also helps you to find undocumented methods during the compilation. The Get method in API looks as follows

image

when you compile the application it shows the following warning in visual studio

image

Add the following attributes to Get API method to generate proper documentation when  there is nothing to return, example follows

image

The above code generates new model named ProblemDetails in Swagger which basically tells your client what went wrong.

image

This is new feature which produces structured responses like  200, 404 and default

image

Instead of adding the above attributes to each API method, you can control the response at API level by including API conventions feature

image

It basically saying add ApiConventionType assembly of type DefaultApiConventions. You can also your own type if you want but the default one supports all get , post, put, update , Find etc. It basically add the attributes to your API methods.

Hope this post help to make your APIs look prettier 🙂

About the author

Kalyan Bandarupalli

My name is kalyan, I am a software architect and builds the applications using Microsoft .NET technologies. Here I am trying to share what I feel and what I think with whoever comes along wandering to Internet home of mine.I hope that this page and its contents will speak for me and that is the reason I am not going to say anything specially about my self here.

2 Comments

  • Is there any chance you would cover the use and configuration with Swashbuckle.AspNetCore in
    ASP.NET Core API 2.2 (not ASP.NET Core MVC 2.2).

TechBubbles Microsoft Technology BLOG

Follow me

Archives

Tag Cloud