I'm designing a JSON API, and I'd like to version the API using content negotiation of some kind. I'm currently planning on using Vendor MIME Types to do this.
While I can definitely do this at the application level, I'm thinking it would be best to make this happen at the HTTP server level. Is this possible with Apache or nginx?
The Content-Type would look something like: application/vnd.vendorname-v1+json
or possibly using parameters: application/vnd.vendorname+json;v=1
Nginx's idiomatic approach to this kind of problems is via
map
. Please see my answer at StackOverflow.Basically, you define a
map
inhttp
sectionYou may mix exact matches and regexps in one map.
Then you simply use
$my_upstream
in youserver
orlocation
section(s):Nginx evaluates map variables lazily, only once (per request) and when you are using them.
Sure; Apache's
mod_rewrite
could do this with a little bit ofRewriteCond
, though I'm a bit too rusty to give you an example off the top of my head. In nginx, though, it'd look something like the following (assuming you had two upstreams defined; one for your jsonapp and the other for... otherstuff):I'm going to go against what the others have suggested.
I think it's a really bad idea to rely on versioning your JSON API from the HTTP server. The HTTP server knows nothing about the API you're developing. It's like defining the Linux version in a text file instead of building it into the kernel source. It makes upgrades more complicated.
All it needs is a mis-configuration down the road and it might all go belly up for the next guy who didn't know about the complicated setup.
Without knowing much about what you're doing there must be a way of making it obtainable using your scripting language (Are you using a scripting language or is this a custom JSON responder?). i.e. like a global variable that is available in javascript. Or returning it on request, a JSON request to get the API version. Or always sending it in all JSON responses at the front of the response. It's very little text after all.
Use the K.I.S.S. approach and you won't regret this.