I want to enable versioning in my REST service via urls. Need some suggestions/feedback on which is better mechanism?
where v1 is the version. I am asking this because a lot of articles mention it like
v1/<myapp_context>/<sub_context> but according to me if more than one service is deployed on machine than it would not look good as,
v1/app1/get v1/app2/get v1/app3/get
Is there any advantage of providing version in the beginning?
Usually, an API is a single coherent system. While it contains multiple resources, these are all related. The API is deployed as a single software.
But it doesn't have to be that way. The API can also be aggregated from multiple sub-APIs that are largely unrelated to each other and are deployed independently. The API server then performs some routing to translate requests to the correct sub-API.
If your API is a single system, then providing a single version at the root is simplest. This is especially the case when you don't yet need that flexibility. In particular, this allows you to later introduce URLs like
/v2/some-sub-api/v7/foo that combine versioning at the root and separate versioning for sub-APIs. You likely don't know in advance where you will need to introduce versioning of sub-APIs.
If the API consists of truly separate sub-APIs (and is also clearly architected and documented like this), then separate versions can make sense. But this introduces a lot of complexity into your URL design. Unless your API is truly gigantic, it might be better to avoid this and expose a unified API.
Note that it's not necessary to “mount” an API at the root of a domain. I.e. it is perfectly legitimate to use
example.com/some-app/api/<API> instead of
some-app-api.example.com/<API>. However, be aware that sharing a domain also implies that e.g. cookies and other security-relevant properties are shared. This may or may not be desirable. This is more relevant if your APIs are supposed to be used via Ajax requests, less relevant for APIs that will only be used by custom software.
I want to enable versioning in my REST service via urls.
Best choice: plan for compatibility in your design, such that changes to your implementation do not break existing clients. Cool URI don't change.
Next best choice: a new api is deployed to a new host. Fielding, in 2014
It is always possible for some unexpected reason to come along that requires a completely different API, especially when the semantics of the interface change or security issues require the abandonment of previously deployed software. My point was that there is no need to anticipate such world-breaking changes with a version ID. We have the hostname for that. What you are creating is not a new version of the API, but a new system with a new brand.
There's really not a lot of difference here -- it's worth considering whether one or the other of these is going to be more useful when clients are performing relative resolution of URI.