Rules to Better OpenAPI Specification
RuleSummaryIntro
AKA OAS. Previously known as Swagger.
Hold on a second! How would you like to view this content?
Just the title!
A brief blurb!
Gimme everything!
Page Content
Know the best OpenAPI toolchain:
swashbuckle
- Good Example (more comprehensive)
www.northwind.com/swagger
- Bad example - default but now it is about help for your API)
www.northwind.com/dev
OR
www.northwind.com/developer
- Bad examples
www.northwind.com/api
- Bad example - already taken
www.northwind.com/help
- Bad example - too broad
www.northwind.com/docs
- Good example - preferred URL
If your changes to your WebAPI break your client, then you want to know right away.
Using NSwag you should generate your API client eg. Angular Client.
- You run nswag.exe on the post-build event
- Nswag will generate the client code and update the API client file directly
-

- Figure: Good example – using NSwag config file helps with automation. Since the API client is generated automatically next time we build, any breaking changes will be obvious immediately
Now this is automated this is no longer a concern we need to deal with.
More info:
http://www.codingflow.net/building-single-page-applications-on-asp-net-core-2-1-with-angular-6-part-3-implementing-open-api/
It is important to define your response types.

dd>Figure: Bad example – no response types

- Figure: Good example – Response types (in .NET)
/// <summary>
/// Returns the nth number in the fibonacci sequence.
/// </summary>
/// <param name="n">The index (n) of the fibonacci sequence</param>
/// <returns>Returns the nth fibonacci number.</returns>
/// <response code="200">int64</response>
[HttpGet]
[ProducesResponseType(200)]
[ProducesResponseType(400)]
[ResponseCache(CacheProfileName = DefaultCacheProfile.Name)]
[Produces("application/json", "text/json")]
public ActionResult<long> Get(long n)
{
_logger.LogInformation($"Fibonacci number {n} requested");
if(!_fibonacciSolver.CanSolve(n))
return new BadRequestResult();
try
{
return _cache.GetOrAdd($"Fibonacci{n}", () => _fibonacciSolver.Solve(n));
}
catch (ArgumentOutOfRangeException)
{
return new BadRequestResult();
}
}
- Figure: Good example for swashbuckle - Even better if you have .NET Core 2.1 use the strong typed ActionResult – see yellow
[HttpGet]
[SwaggerResponse(HttpStatusCode.OK, typeof(long))]
[SwaggerResponse(HttpStatusCode.BadRequest, typeof(void))]
public ActionResult<long> Get(long n)
{
_logger.LogInformation($"Fibonacci number {n} requested");
if(!_fibonacciSolver.CanSolve(n))
return new BadRequestResult();
try
{
return _cache.GetOrAdd($"Fibonacci{n}", () => _fibonacciSolver.Solve(n));
}
catch (ArgumentOutOfRangeException)
{
return new BadRequestResult();
}
}
- Figure: Good example for nswag - Even better if you have .NET Core 2.1 use the strong typed ActionResult – see yellow