Versioning WebApi and documenting version with Swagger

Versioning in WebApi

Note: This post draws alot of points from https://www.troyhunt.com/your-api-versioning-is-wrong-which-is/ – but is more about implementation and documentation through swagger.
So please go read Troy’s post and then come back :).
There are a couple of ways of versioning a restful api
among them are:
1. Url versioning e.g. GET http://example.com/api/v1/cars
2. Request-Header e.g. GET http://example.com/api/cars — Header: api-version: 1
There are pros and cons in both regards, Troy gets around them quite nicely.
Time to code!

Url Versioning

Easy – simply use either the RoutePrefix- or RouteAttribute

Read more about the Routing-Attribute here

Request-Header

Drawing from Troy’s post
We create a new attribute which uses a custom routing constraint

** Usage **

Effectively matching routes based on the “api-version” header.

Swagger

When using swashbuckle (swagger implementation for .Net).
It knows about the default Route- and RoutePrefixAttribute, so Url Versioning is taken care of, out of the box.
But Header versioning is not.
Fortunately, it’s quite easy to implement an OperationFilter that adds the header as a parameter to the endpoints in question.
This implementation uses a list of versions and the endpoints relativepaths to know when to add the parameter and when not to.


How would you implement the OperationFilter?