Swagger is a tool which lets you describe the structure of your APIs in a machine readable format. Swagger achieves this by inspecting your APIs to generate a YAML or JSON file which contains a detailed description of your entire API. The description includes the information like:
- List of all operations that API supports.
- What are API parameters and what it returns?
- Does API require any Authorization?
- Other information such as API License details, terms and contact information.
Swagger implements the OpenAPI Specification and automates the entire documentation process, making it effortless for your teams to generate and maintain them. It works in conjunction with Swagger UI so it generates user-friendly and interactive API documentation. This lets your team use the API call right from the browser without aid of any third-party tool like Fiddler, Postman etc. Swagger UI allows your development team, your end consumers or just about anyone to visualize and interact with the API’s resources without exposing any implementation details.
Create a new .NET Core 2.0 Web API project and install Swashbuckle.AspNetCore nuget package:
The Swashbuckle.AspNetCore metapackage contains three components:
- Swashbuckle.AspNetCore.Swagger: A middleware to expose Swagger specification document as JSON endpoints from APIs
- Swashbuckle.AspNetCore.SwaggerGen: A Swagger Generator that inspects the controller, routes and models to generate Swagger specification document for APIs
- Swashbuckle.AspNetCore.SwaggerUI: A Swagger UI tool. It reads the Swagger JSON to build a rich UI for describing the Web API functionality. It also comes with a built-in test harnesses which lets users interact with APIs.
With Swashbuckle package installed we now need to make a couple of changes in the ConfigureServices method of Startup.cs class to get everything going. First, add the Swagger Generator to the services collection.
To use Info, Contact and License class you need to import the following namespace:
Now, we need to enable the middleware for serving the generated JSON document and Swagger UI. To enable the middleware, update the Configure method of Startup class.
The UseSwagger method serves the generated JSON document at http://localhost:<port>/swagger/v1/swagger.json
The UseSwaggerUI method serves the Swagger UI at http://localhost:<port>/swagger
The Swagger UI can also be served at the app’s root (http://localhost:<port>/), for that set the RoutePrefix property to an empty string.
Now run the application and navigate to the application root. You should see the output like the one shown below:
Enabling XML comments:
Here’s how you enable XML comments: right click on the Web API project and select properties, then navigate to the Build tab. Under Output check the XML documentation file box. This will generate the XML documentation file for the Debug mode.
For release mode change Configuration to Release and again check the XML documentation file box.
Now, we will configure Swagger to consume this file. To do so, we need to pass this file to AddSwaggerGen method. Update the Swagger generator registration as shown below:
The generated XML documentation file has the same name as that of the Web API project. The AppContext.BaseDirectory property gets the location of the XML file.
Now it’s time to add comments to the action methods. To add triple slash comments type 3 forward slashes above the method name and visual studio will auto-generate the comment section. Add the comments between <summary> tags and run the solution. The comments will be displayed in UI as shown below:
You can also add more robust comments. Just add a <remarks> section in the comments as described below.
Display enum as strings
By default, Swagger displays enums as intergers in Swagger UI. In order to display enum values as a strings add DescribeAllEnumsAsStrings to AddSwaggerGen method in Startup class. To display enum string values in camel case use DescribeStringEnumsInCamelCase.
Describing response types
Swagger generates a “200” response of all operations. If any action method returns a model then it will be utilized to generate a schema for the response body.
In certain instances, we may want to return different response codes for the operations performed by the action methods. We can describe those responses in the Swagger documentation by decorating the corresponding action methods with ProducesResponseType attribute.
We can also customize the description of a response codes by adding the response tag in the comments section above action method.
Multiple API Versions
Swagger supports API versioning. Using Swagger, we can create multiple documentations for the different versions of API. Adding versioning to Swagger requires a couple of updates in the Startup class. We need to add an additional Swagger document using SwaggerDoc for version ‘v2’. Then configure the same for Swagger UI using SwaggerEndpoint.
By default, Swashbuckle will include all API endpoints in both documents, so we will have to inform Swashbuckle which API endpoints to include in each document. This can be achieved either by decorating Individual Actions or by applying an application wide convention.
In case of decorating individual actions, we will have to decorate each action with the ApiExplorerSettingsAttribute and set GroupName to the corresponding document name (case sensitive):
In case of group by convention, we will have to first apply a custom controller/action naming convention across the application. Then we will have to configure the following convention by invoking DocInclusionPredicate in AddSwaggerGen to assign the corresponding actions to documents.
Customizing Swagger UI
The look and feel of the default UI that’s shipped with Swagger UI package can be customized by injecting custom CSS stylesheets. For customizing the Swagger UI, create a new CSS file (custom.css) in the wwwroot/css folder of the API project. Now, inject it in the middleware with InjectStylesheet method.