Exposing ASP.Net Core Web API Documentation with Swagger
Swagger is one of the available options for API documentation and code generation. In this post, we are going to build swagger specification on top of the Student Service built in the last post [http://www.alternatestack.com/development/app-development/creating-web-apis-with-aspnet-core/] using ASP.Net Core.
Let’s first add the required nuget packages. Here we are using SwaggerGen and SwaggerUI packages. Here the former is used to generate swagger spec for the API and latter is used to expose the specification through a pretty UI. The packages are still in beta for ASP.Net Core.
After adding the above to project.json, let’s run dotnet restore command to download these packages to universal packages folder.
The packages provide a number of extension methods to IServiceCollection and IApplicationBuilder. Now we can use the functionality exposed by these packages in Startup class. Let’s first look at ConfigureService method. Here we are adding certain metadata to the service using ConfigureSwaggerGen method. This metadata would be part of specification, also exposed through ui.
Another is Configure method. Here we are using both Swagger specification generation and UI functionality by using UseSwagger() and UseSwaggerUI() methods.
Service Spec
Let’s run this using dotnet run. Here we are hosting it on localhost:5000 (default) so the url for the spec would be http://localhost:5000/swagger/v1/swagger.json. Here are the contents for the spec.
You can copy and paste this in the editor of your choice and format it as pretty json to understand the API.
Service Documentation
Service documentation can be viewed using Swagger UI. It lists all the operations exposed by the service alongside their signatures. Our service should be available at http://localhost:5000/swagger/ui/index.html
Swagger-ui also allows us to test the API as a client. Here we can specify different parameters to the service to test the service response.
Using Code’s XML Comments
Swagger also supports the code’s xml comments to be used for documentation of our API. You just need to enable it like this in project.json.
Here is how we have added the xml comments to the service and its operations:
Please notice the operation summary being used as description for service operations.
Using Swashbuckle’s attributes
Swashbuckle also provides attributes for decorating our operations. These attributes are available in Swashbuckle.SwaggerGen.Annotations namespace. Let’s add these attributes to our Students service. Here we are adding SwaggerOperation attribute to all our operations. Additionally, we have added SwaggerResponse attribute to Get() method. Here we can list all the possible responses with HTTP status codes.
Please notice how SwaggerOperation translates in swagger spec for get-students-list operation. You can also notice Exception response for Unauthorized.
Here is how Swagger UI displays it.