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
Install NSwag.AspNetCore Nuget package for Swagger. Add following lines in Startup.cs file. More about NSwag can be read from here.
Run the application and hit Swagger end-point then you see the following screen
It describes your application and endpoints and models in your API. You can test Get method by clicking try out and hit execute button
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
when you compile the application it shows the following warning in visual studio
Add the following attributes to Get API method to generate proper documentation when there is nothing to return, example follows
The above code generates new model named ProblemDetails in Swagger which basically tells your client what went wrong.
This is new feature which produces structured responses like 200, 404 and default
Instead of adding the above attributes to each API method, you can control the response at API level by including API conventions feature
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 🙂
Very helpful article for developers to expose their API signatures to the clients using Swagger.
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).