13 KiB
title | author | description | manager | ms.author | ms.custom | ms.date | ms.prod | ms.technology | ms.topic | uid |
---|---|---|---|---|---|---|---|---|---|---|
Get started with Swashbuckle and ASP.NET Core | zuckerthoben | Learn how to add Swashbuckle to your ASP.NET Core project to integrate the Swagger UI. | wpickett | scaddie | mvc | 03/15/2018 | asp.net-core | aspnet | article | tutorials/get-started-with-swashbuckle |
Get started with Swashbuckle and ASP.NET Core
By Shayne Boyer and Scott Addie
There are three main components to Swashbuckle:
-
Swashbuckle.AspNetCore.Swagger: a Swagger object model and middleware to expose
SwaggerDocument
objects as JSON endpoints. -
Swashbuckle.AspNetCore.SwaggerGen: a Swagger generator that builds
SwaggerDocument
objects directly from your routes, controllers, and models. It's typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON. -
Swashbuckle.AspNetCore.SwaggerUI: an embedded version of the Swagger UI tool which interprets Swagger JSON to build a rich, customizable experience for describing the Web API functionality. It includes built-in test harnesses for the public methods.
Package installation
Swashbuckle can be added with the following approaches:
Visual Studio
-
From the Package Manager Console window:
Install-Package Swashbuckle.AspNetCore
-
From the Manage NuGet Packages dialog:
- Right-click your project in Solution Explorer > Manage NuGet Packages
- Set the Package source to "nuget.org"
- Enter "Swashbuckle.AspNetCore" in the search box
- Select the "Swashbuckle.AspNetCore" package from the Browse tab and click Install
Visual Studio for Mac
- Right-click the Packages folder in Solution Pad > Add Packages...
- Set the Add Packages window's Source drop-down to "nuget.org"
- Enter Swashbuckle.AspNetCore in the search box
- Select the Swashbuckle.AspNetCore package from the results pane and click Add Package
Visual Studio Code
Run the following command from the Integrated Terminal:
dotnet add TodoApi.Swashbuckle.csproj package Swashbuckle.AspNetCore
.NET Core CLI
Run the following command:
dotnet add TodoApi.Swashbuckle.csproj package Swashbuckle.AspNetCore
Add and configure Swagger middleware
Add the Swagger generator to the services collection in the Startup.ConfigureServices
method:
Import the following namespaces in the Info
class:
using Swashbuckle.AspNetCore.Swagger;
In the Startup.Configure
method, enable the middleware for serving the generated JSON document and the Swagger UI:
Launch the app, and navigate to http://localhost:<random_port>/swagger/v1/swagger.json
. The generated document describing the endpoints appears as shown in Swagger specification (swagger.json).
The Swagger UI can be found at http://localhost:<random_port>/swagger
. Now you can explore the API via Swagger UI and incorporate it in other programs.
Customize & extend
Swagger provides options for documenting the object model and customizing the UI to match your theme.
API info and description
The configuration action passed to the AddSwaggerGen
method can be used to add information such as the author, license, and description:
The following image depicts the Swagger UI displaying the version information:
XML comments
XML comments can be enabled with the following approaches:
Visual Studio
- Right-click the project in Solution Explorer and select Properties
- Check the XML documentation file box under the Output section of the Build tab:
Visual Studio for Mac
- Open the Project Options dialog > Build > Compiler
- Check the Generate xml documentation box under the General Options section:
Visual Studio Code
Manually add the following snippet to the .csproj file:
Enabling XML comments provides debug information for undocumented public types and members. Undocumented types and members are indicated by the warning message. For example, the following message indicates a violation of warning code 1591:
warning CS1591: Missing XML comment for publicly visible type or member 'TodoController.GetAll()'
Suppress warnings by defining a semicolon-delimited list of warning codes to ignore in the .csproj file:
Configure Swagger to use the generated XML file. For Linux or non-Windows operating systems, file names and paths can be case sensitive. For example, a TodoApi.Swashbuckle.XML file is valid on Windows but not CentOS.
In the preceding code, ApplicationBasePath
gets the base path of the app. The base path is used to locate the XML comments file. TodoApi.Swashbuckle.xml only works for this example, since the name of the generated XML comments file is based on the application name.
Adding the triple-slash comments to the method enhances the Swagger UI by adding the description to the section header:
The UI is driven by the generated JSON file, which also contains these comments:
"delete": {
"tags": [
"Todo"
],
"summary": "Deletes a specific TodoItem.",
"operationId": "ApiTodoByIdDelete",
"consumes": [],
"produces": [],
"parameters": [
{
"name": "id",
"in": "path",
"description": "",
"required": true,
"type": "integer",
"format": "int64"
}
],
"responses": {
"200": {
"description": "Success"
}
}
}
Add a <remarks> tag to the Create
action method documentation. It supplements information specified in the <summary> tag and provides a more robust Swagger UI. The <remarks>
tag content can consist of text, JSON, or XML.
Notice the UI enhancements with these additional comments.
Data annotations
Decorate the model with attributes, found in the System.ComponentModel.DataAnnotations namespace, to help drive the Swagger UI components.
Add the [Required]
attribute to the Name
property of the TodoItem
class:
The presence of this attribute changes the UI behavior and alters the underlying JSON schema:
"definitions": {
"TodoItem": {
"required": [
"name"
],
"type": "object",
"properties": {
"id": {
"format": "int64",
"type": "integer"
},
"name": {
"type": "string"
},
"isComplete": {
"default": false,
"type": "boolean"
}
}
}
},
Add the [Produces("application/json")]
attribute to the API controller. Its purpose is to declare that the controller's actions support a response content type of application/json:
The Response Content Type drop-down selects this content type as the default for the controller's GET actions:
As the usage of data annotations in the Web API increases, the UI and API help pages become more descriptive and useful.
Describe response types
Consuming developers are most concerned with what is returned—specifically response types and error codes (if not standard). These are handled in the XML comments and data annotations.
The Create
action returns 201 Created
on success or 400 Bad Request
when the posted request body is null. Without proper documentation in the Swagger UI, the consumer lacks knowledge of these expected outcomes. That problem is fixed by adding the highlighted lines in the following example:
The Swagger UI now clearly documents the expected HTTP response codes:
Customize the UI
The stock UI is both functional and presentable; however, when building documentation pages for your API, you want it to represent your brand or theme. Accomplishing that task with the Swashbuckle components requires adding the resources to serve static files and then building the folder structure to host those files.
If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project:
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />
The preceding NuGet package is already installed if targeting .NET Core 2.x and using the metapackage.
Enable the static files middleware:
Acquire the contents of the dist folder from the Swagger UI GitHub repository. This folder contains the necessary assets for the Swagger UI page.
Create a wwwroot/swagger/ui folder, and copy into it the contents of the dist folder.
Create a wwwroot/swagger/ui/css/custom.css file with the following CSS to customize the page header:
Reference custom.css in the index.html file:
Browse to the index.html page at http://localhost:<random_port>/swagger/ui/index.html
. Enter http://localhost:<random_port>/swagger/v1/swagger.json
in the header's textbox, and click the Explore button. The resulting page looks as follows:
There's much more you can do with the page. See the full capabilities for the UI resources at the Swagger UI GitHub repository.