4

What is the best approach to version WebAPIs?

I am building an API from scratch and I would like to ensure that it will version gracefully in the future. I am envisioning something like mysite.com/api/v2/...

One approach I see is to create a separate project (web app) for each version of API. But perhaps there are better ways to do it?

Thank you for your ideas.

Alex Avrutin
  • 1,344
  • 2
  • 17
  • 24

2 Answers2

4

Including version number in the URL is the standard approach as I explained in this post (I do not repeat the content): Implementing versioning a RESTful API with WCF or ASP.Net Web Api

You do not need to create a completely new project although you can. The problem that you will be facing with a single project is that there will be collision of names:

/api/v1.0/Car/123

and

/api/v2.0/Car/123

both will point to CarController while you can have only one of those. The solution would be to implement your own IHttpControllerSelector and register with the DependencyResolver. This implementation will look at the version number and perhaps find the type based on the namespace.


UPDATE

I do not intend to start a REST controversy here. But as @DarrelMiller points out, here is an older discussion on the same subject discouraging my suggested approach:

How to version REST URIs

I personally think URL versioning is the way to go.

Community
  • 1
  • 1
Aliostad
  • 80,612
  • 21
  • 160
  • 208
3

You will need to create your own implementation of IHttpControllerSelector. The best way is to base this implementation on Microsoft's IHttpControllerSelector. Then you can decide in your IHttpControllerSelectorif you want to version by URL or by content-type.

The most basic implementation directly implements IHttpControllerSelector and just implements the SelectController method but performance reasons it is better to implement some caching around it.

For finding the Controller you simple the IHttpControllerTypeResolver instance you can get using HttpConfiguration.Services.

I've used something like this: http://damsteen.nl/blog/implementing-versioning-in-asp.net-web-api. Also put some code on Github: https://github.com/Sebazzz/SDammann.WebApi.Versioning.

Sebazzz
  • 1,205
  • 2
  • 15
  • 33