Swashbuckle

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
2
3
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

update your program.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
:
//
// https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-6.0&tabs=visual-studio
// The call to AddEndpointsApiExplorer shown in the preceding example is required only for minimal APIs.
builder.Services.AddEndpointsApiExplorer();

// get appSettings.json data
var environmentName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");

// load up the config file, load AppSettings.json and the environment specific one.
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environmentName}.json", true, reloadOnChange: true)
.Build();


:
// This is from https://www.youtube.com/watch?v=GZY7M4v-d68
//
// it instructs swashbuckler to scan code for comments that are used
// to document the controllers. It will add some of those comments to
// your .XML definition file
//
builder.Services.AddSwaggerGen(
c =>
{ //
// this is version 1. recently I have taken this out and replaced it
// with the version 2 below.
//
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
//
// version 2
//
c.SwaggerDoc("v1", new OpenApiInfo
{ Title = "Notes API", Version = "v1" });
c.EnableAnnotations();
c.ExampleFilters();

try
{
var filePath = Path.Combine(AppContext.BaseDirectory, "Note.API.xml");
c.IncludeXmlComments(filePath);
}
catch
{
}
});

// this is used if you are using the filters.
builder.Services.AddSwaggerExamplesFromAssemblies(Assembly.GetEntryAssembly());

:
if (isDevelopment)
{
//
// Actually, this isn't swagger. But if you are running in developement
// then if there's an error, this next function will show more information
// about the error
//
app.UseDeveloperExceptionPage();

//
// here are the swagger commands
app.UseSwagger();
//
// this is version 1. I have since replaced it with version 2
//
app.UseSwaggerUI();
//
// version 2
//
// this creates the 2 urls
// https://localhost:7230/swagger/v1/swagger.json - to see the json
// https://localhost:7230/swagger/index.html - to see the stuff
app.UseSwaggerUI(c => c.SwaggerEndpoint(
"/swagger/v1/swagger.json",
"Notes API V1"));
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[Route("api/v1/[controller]")]
[ApiController]
public class BankAccountsController : BaseController
{
private readonly IBankAccountService _bankAccountService;

public BankAccountsController(IBankAccountService bankAccountService)
{
_bankAccountService = bankAccountService;
}

// Get: api/bankAccounts
[HttpGet]
public IActionResult GetAll()
{
return ReturnResult(_bankAccountService.GetAllBankAccounts());
}
:

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    public class BaseController : ControllerBase
{
[NonAction]
public IActionResult ReturnResult<T>(IResult<T> result)
{
return Ok(result);
}
:
````

### Missing XML comment for publicly visible type or member



## Adding notes that showup in the API documentation to your methods.

Here is an example:

````C
/// <summary>
/// Retreives a list of that have been added to the database.
/// </summary>
/// <remarks>
/// Sorted by AccountNumberDescription
/// </remarks>
/// <example>
/// https://localhost:7230/api/v1/accountNumbers
/// </example>
[HttpGet]
public IActionResult GetAll()
{
return ReturnResult(_accountNumberService.GetAllAccountNumbers());
}

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
2
3
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

References