Open api is a standard for documenting API’s
Swashbuckle helps the developer document their API’s
One way to use this tool is to put certain types of comments in front of each of the methods of your controller classes. Swashbuckle will turn that into an XML file. It also will routes to your API to initiatlize the XML file, and another one to view the API in a fairly nice format. There’s another package which when integrated will give warning messages reminding you where documentation is needed.
Install Nuget Libraries
Use Nuget to install the following Libraries:
- Swashbuckle.AspNetCore
- Swashbuckle.AspNetCore.Annotations - Optional - Used if you are adding swashbuckle based annotations
- Swashbuckle.AspNetCore.Filters - Optional - Used if you are adding examples to the swagger output.
Update your Project file - using the Project’s Properties page.
Check the ‘Documentation File’ checkbox.
Update your csProj file
Add the following property group
1 | <PropertyGroup> |
update your program.cs
1 | : |
Testing Swagger
First … Make sure your API still works.
for me:
1 | https://localhost:7230/ |
Gives me a hello world message. That shows me my API is basically working.
Try the following command
1 | https://localhost:7230/swagger/v1/swagger.json |
This gives you the API documentation showing you the interface. This is the actual API presented as a .JSON file.
Try the following command
1 | https://localhost:7230/swagger/index.html |
This provides an human readable web page showing you the API that you can use to view the api, and even test the API (using buttons marked ‘Try it out’)
todo: Add launchSettings
Troubleshooting
The first time I executed this code, I was getting errors.
it turns out, for your controlling classes, you are expected to have each method properly annotated
1 | [Route("api/v1/[controller]")] |
The class declaration includes Route and ApiController tags, each method (except for the constructor) contains a tags like [HttpGet], [HttpPut].
This is what is expected. And with the way I write controller objects it made sense and that’s what I did.
My problem is each of my controllers inherit the BaseController class. My BaseController was not annotated.
I added [NoAction] tags to each of the methods
1 | public class BaseController : ControllerBase |
The [HttpGet] tag was added to the Json file with a few basic notes
Swashbuckle looks for \\ (3 slashes) for OpenAPI notes. When It find them it looks for tags like <summary>, <remarks>, <examples>, <param name=”xx”>, <returns>, <response code=”xxx”>
It looks for a few other Annotations as well, for example [Required]
Note: If this isn’t working, add the following to your csProj file.
1 | <PropertyGroup> |