After having read a lot of material on REST versioning, I am thinking of versioning the calls instead of the API. For example:
http://api.mydomain.com/callfoo/v2.0/param1/param2/param3
http://api.mydomain.com/verifyfoo/v1.0/param1/param2
instead of first having
http://api.mydomain.com/v1.0/callfoo/param1/param2
http://api.mydomain.com/v1.0/verifyfoo/param1/param2
then going to
http://api.mydomain.com/v2.0/callfoo/param1/param2/param3
http://api.mydomain.com/v2.0/verifyfoo/param1/param2
The advantage I see are:
When the calls change, I do not have to rewrite my entire client - only the parts that are affected by the changed calls.
Those parts of the client that work can continue as is (we have a lot of testing hours invested to ensure both the client and the server sides are stable.)
I can use permanent or non-permanent redirects for calls that have changed.
Backward compatibility would be a breeze as I can leave older call versions as is.
Am I missing something? Please advise.
Require an HTTP header.
Version: 1
The Version header is provisionally registered in RFC 4229 and there some legitimate reasons to avoid using an X- prefix or a usage-specific URI. A more typical header was proposed by yfeldblum at https://stackoverflow.com/a/2028664:
X-API-Version: 1
In either case, if the header is missing or doesn't match what the server can deliver, send a 412 Precondition Failed response code along with the reason for the failure. This requires clients to specify the version they support every single time but enforces consistent responses between client and server. (Optionally supporting a ?version= query parameter would give clients an extra bit of flexibility.)
This approach is simple, easy to implement and standards-compliant.
Alternatives
I'm aware that some very smart, well-intentioned people have suggested URL versioning and content negotiation. Both have significant problems in certain cases and in the form that they're usually proposed.
URL Versioning
Endpoint/service URL versioning works if you control all servers and clients. Otherwise, you'll need to handle newer clients falling back to older servers, which you'll end up doing with custom HTTP headers because system administrators of server software deployed on heterogeneous servers outside of your control can do all sorts of things to screw up the URLs you think will be easy to parse if you use something like 302 Moved Temporarily.
Content Negotiation
Content negotiation via the Accept header works if you are deeply concerned about following the HTTP standard but also want to ignore what the HTTP/1.1 standard documents actually say. The proposed MIME Type you tend to see is something of the form application/vnd.example.v1+json. There are a few problems:
There are cases where the vendor extensions are actually appropriate, of course, but slightly different communication behaviors between client and server doesn't really fit the definition of a new 'media type'. Also, RFC 2616 (HTTP/1.1) reads, "Media-type values are registered with the Internet Assigned Number Authority. The media type registration process is outlined in RFC 1590. Use of non-registered media types is discouraged." I don't want to see a separate media type for every version of every software product that has a REST API.
Any subtype ranges (e.g., application/*) don't make sense. For REST APIs that return structured data to clients for processing and formatting, what good is accepting */* ?
The Accept header takes some effort to parse correctly. There's both an implied and explicit precedence that should be followed to minimize the back-and-forth required to actually do content negotiation correctly. If you're concerned about implementing this standard correctly, this is important to get right.
RFC 2616 (HTTP/1.1) describes the behavior for any client that does not include an Accept header: "If no Accept header field is present, then it is assumed that the client accepts all media types." So, for clients you don't write yourself (where you have the least control), the most correct thing to do would be to respond to requests using the newest, most prone-to-breaking-old-versions version that the server knows about. In other words, you could have not implemented versioning at all and those clients would still be breaking in exactly the same way.
Edited, 2014:
I've read a lot of the other answers and everyone's thoughtful comments; I hope I can improve on this with the benefit of a couple of years of feedback:
Don't use an 'X-' prefix. I think Accept-Version is probably more meaningful in 2014, and there are some valid concerns about the semantics of re-using Version raised in the comments. There's overlap with defined headers like Content-Version and the relative opaqueness of the URI for sure, and I try to be careful about confusing the two with variations on content negotiation, which the Version header effectively is. The third 'version' of the URL https://example.com/api/212315c2-668d-11e4-80c7-20c9d048772b is wholly different than the 'second', regardless of whether it contains data or a document.
Regarding what I said above about URL versioning (endpoints like https://example.com/v1/users, for instance) the converse probably holds more truth: if you control all servers and clients, URL/URI versioning is probably what you want. For a large-scale service that could publish a single service URL, I would go with a different endpoint for every version, like most do. My particular take is heavily influenced by the fact that the implementation as described above is most commonly deployed on lots of different servers by lots of different organizations, and, perhaps most importantly, on servers I don't control. I always want a canonical service URL, and if a site is still running the v3 version of the API, I definitely don't want a request to https://example.com/v4/ to come back with their web server's 404 Not Found page (or even worse, 200 OK that returns their homepage as 500k of HTML over cellular data back to an iPhone app.)
If you want very simple /client/ implementations (and wider adoption), it's very hard to argue that requiring a custom header in the HTTP request is as simple for client authors as GET-ting a vanilla URL. (Although authentication often requires your token or credentials to be passed in the headers, anyway. Using Version or Accept-Version as a secret handshake along with an actual secret handshake fits pretty well.)
Content negotiation using the Accept header is good for getting different MIME types for the same content (e.g., XML vs. JSON vs. Adobe PDF), but not defined for versions of those things (Dublin Core 1.1 vs. JSONP vs. PDF/A). If you want to support the Accept header because it's important to respect industry standards, then you won't want a made-up MIME Type interfering with the media type negotiation you might need to use in your requests. A bespoke API version header is guaranteed not to interfere with the heavily-used, oft-cited Accept, whereas conflating them into the same usage will just be confusing for both server and client. That said, namespacing what you expect into a named profile per 2013's RFC6906 is preferable to a separate header for lots of reasons. This is pretty clever, and I think people should seriously consider this approach.
Adding a header for every request is one particular downside to working within a stateless protocol.
Malicious proxy servers can do almost anything to destroy HTTP requests and responses. They shouldn't, and while I don't talk about the Cache-Control or Vary headers in this context, all service creators should carefully consider how their content is consumed in lots of different environments.
This is a matter of opinion; here's mine, along with the motivation behind the opinion.
include the version in the URL.
For those who say, it belongs in the HTTP header, I say: maybe. But putting in the URL is the accepted way to do it according to the early leaders in the field. (Google, yahoo, twitter, and more). This is what developers expect and doing what developers expect, in other words acting in accordance with the principle of least astonishment, is probably a good idea. It absolutely does not make it "harder for clients to upgrade". If the change in URL somehow represents an obstacle to the developer of a consuming application, as suggested in a different answer here, that developer needs to be fired.
Skip the minor version
There are plenty of integers. You're not gonna run out. You don't need the decimal in there. Any change from 1.0 to 1.1 of your API shouldn't break existing clients anyway. So just use the natural numbers. If you like to use separation to imply larger changes, you can start at v100 and do v200 and so on, but even there I think YAGNI and it's overkill.
Put the version leftmost in the URI
Presumably there are going to be multiple resources in your model. They all need to be versioned in synchrony. You can't have people using v1 of resource X, and v2 of resource Y. It's going to break something. If you try to support that it will create a maintenance nightmare as you add versions, and there's no value add for the developer anyway. So, http://api.mydomain.com/v1/Resource/12345 , where Resource is the type of resource, and 12345 gets replaced by the resource id.
You didn't ask, but...
Omit verbs from your URL path
REST is resource oriented. You have things like "CallFoo" in your URL path, which looks suspiciously like a verb, and unlike a noun. This is wrong. Use the Force, Luke. Use the verbs that are part of REST: GET PUT POST DELETE and so on. If you want to get the verification on a resource, then do GET http://domain/v1/Foo/12345/verification. If you want to update it, do POST /v1/Foo/12345.
Put optional params as a query param or payload
The optional params should not be in the URL path (before the first question mark) unless you are suggesting that those optional params constitute a self-standing resource. So, POST /v1/Foo/12345?action=partialUpdate¶m1=123¶m2=abc.
Don't do either of those things, because they push the version into the URI structure, and that's going to have downsides for your client applications. It will make it harder for them to upgrade to take advantage of new features in your application.
Instead, you should version your media types, not your URIs. This will give you maximum flexibility and evolutionary ability. For more information, see this answer I gave to another question.
I like using the profile media type parameter:
application/json; profile="http://www.myapp.com/schema/entity/v1"
More Info:
https://www.rfc-editor.org/rfc/rfc6906
http://buzzword.org.uk/2009/draft-inkster-profile-parameter-00.html
It depends on what you call versions in your API, if you call versions to different representations (xml, json, etc) of the entities then you should use the accept headers or a custom header. That is the way http is designed for working with representations. It is RESTful because if I call the same resource at the same time but requesting different representations, the returned entities will have exactly the same information and property structure but with different format, this kind of versioning is cosmetic.
In the other hand if you understand 'versions' as changes in entity structure, for example adding a field 'age' to the 'user' entity. Then you should approach this from a resource perspective which is in my opinion the RESTful approach. As described by Roy Fielding in his disseration ...a REST resource is a mapping from an identifier to a set of entities... Therefore makes sense that when changing the structure of an entity you need to have a proper resource that points to that version. This kind of versioning is structural.
I made a similar comment in: http://codebetter.com/howarddierking/2012/11/09/versioning-restful-services/
When working with url versioning the version should come later and not earlier in the url:
GET/DELETE/PUT onlinemall.com/grocery-store/customer/v1/{id}
POST onlinemall.com/grocery-store/customer/v1
Another way of doing that in a cleaner way but which could be problematic when implementing:
GET/DELETE/PUT onlinemall.com/grocery-store/customer.v1/{id}
POST onlinemall.com/grocery-store/customer.v1
Doing it this way allows the client to request specifically the resource they want which maps to the entity they need. Without having to mess with headers and custom media types which is really problematic when implementing in a production environment.
Also having the url late in the url allows the clients to have more granularity when choosing specifically the resources they want, even at method level.
But the most important thing from a developer perspective, you don't need to maintain the whole mappings (paths) for every version to all the resources and methods. Which is very valuable when you have lot of sub-resources (embedded resources).
From an implementation perspective having it at the level of resource is really easy to implement, for example if using Jersey/JAX-RS:
#Path("/customer")
public class CustomerResource {
...
#GET
#Path("/v{version}/{id}")
public IDto getCustomer(#PathParam("version") String version, #PathParam("id") String id) {
return locateVersion(version, customerService.findCustomer(id));
}
...
#POST
#Path("/v1")
#Consumes(MediaType.APPLICATION_JSON)
public IDto insertCustomerV1(CustomerV1Dto customer) {
return customerService.createCustomer(customer);
}
#POST
#Path("/v2")
#Consumes(MediaType.APPLICATION_JSON)
public IDto insertCustomerV2(CustomerV2Dto customer) {
return customerService.createCustomer(customer);
}
...
}
IDto is just an interface for returning a polymorphic object, CustomerV1 and CustomerV2 implement that interface.
Facebook does verisoning in the url. I feel url versioning is cleaner and easier to maintain as well in the real world.
.Net makes it super easy to do versioning this way:
[HttpPost]
[Route("{version}/someCall/{id}")]
public HttpResponseMessage someCall(string version, int id))
I am creating a RESTful webservice and I have a URL like this:
GET /pets
For normal users this should only return the pets that belongs to that user. But for admin it should return all pets in the system. Is this wrong to do? Or should I instead do this
GET /pets?ownedBy=Smith
and only allow access to the pets if the user is either Smith or an admin?
I don't think REST specifications mentions anything about it specifically. But IMPO, I believe it is perfectly right to return the results as per the requesting user. URLs should be kept as cleaner as possible. If user information is already present as part of headers, then it is not required to provide it in URL redundantly.
While answer from Juned Ahsan is perfectly correct IMHO, I would probably modify your URLs pattern to something like
GET /Smith/pets : return pets for Mr Smith
Authorization can now be done one layer up in the URL and URLs always represent the same resource. I tend to prefer this solution because it will be easier to add a caching layer on top of it. Adding the user (from HTTP header) to the cache key is not efficient, nor is it easy to configure for some caching solution.
I would only provide it in the URL if you also have cases where it is valid to put someone else's name there. For example if people are able to see their friends pet or if and admin is able to see a selected person's pets.
So in the situation where you have a user for that parameter it would make sense to expose it and always use it.
If that is not the case though then simplicity in your API is generally a good thing.
To answer the "can" in your question as well as the "should" though - it's entirely possible. Exactly how to implement it would depend on the framework you are using but they will all support this.
These two URLs are different.
The first one gives a list of pets.
The second one gives also a list of pets, but in this case the list is filtered by the property "owner".There is nothing wrong with this. I would change the second URL slightly to:
GET /pets?owner=Smith
The key with that this URL is, that the type of the result is the same (a list of pet entities), and the meaning is the same too. There is only a filter applied to the list. That is where the query is made for in REST.
In some cases a Path parameter would be better. If you have entities "person", which do have a property of type list of pets, I would create a path like
/<user>/pets
If the list of pets are the root elements I would use a query.
I think it is up to the implementation in the back-end service. Currently, I am working in a similar fashion on a WCF RESTful service (although for Android). And if you have some roles that you can add in your database, it is not so difficult to apply that in your service, and your url would have nothing to do with that.
Edit: If you do want to have something in the URL, you can always add that. But I do not think that it is necessary at all. The less the users see, the better.
As mentioned earlier by Christian Kuetbach using REST you would pass parameters separated by /
i.e. /<userid>/pets if you have any other user specific functionality, or maybe other way around /pets/<userid>. I would suggest using UUID as userID - this way it will ensure user details security
Do I need to make a custom regex pattern to match URLs when I have the following mapping (example):
<url-mapping id="approvedQuestions">
<pattern>/questions/approved/#{viewOption}/</pattern>
<view-id>/approved.xhtml</view-id>
</url-mapping>
where the viewoption-portion should also match when the user does NOT end the URL with '/'?
And is it possible to supply some kind of default value if the don't add the viewOption portion at all?
And if I the viewOption is a enum, is it possible to lowercase the parameter? Now I have to write uppercase in to make it work.
You can use a custom regex to do this type of, but I recommend using a url-rewrite rule to append a trailing slash if one is missing. You should pick one URL (with or without the '/' at the end) otherwise you are actually serving up the same resources with two distinct addresses, and you will be punished by search engines and other crawlers.
To do this, I would use a rewrite rule such as the following:
<rewrite match="/questions/approved/[^/]+" trailingSlash="append" />
This will cause the server to detect when a '/' is missing from the end of the URL, and it will redirect the request to the proper location, with a '/' at the end.
In order to address your enum issue, this is a bit more complicated. We don't typically recommend binding values directly into enumerations. In this case, you are not actually binding into an enum (I'm guessing,) but are actually binding the literal string URL value into the request scoped EL context. This value is then being extracted somewhere else in your application, and that is where the conversion into an ENUM is taking place.
Until PrettyFaces 4 comes out, I recommend instead binding the value into a String location, then using an action method to do the loading of the correct value yourself, like so:
<url-mapping id="approvedQuestions">
<pattern>/questions/approved/#{params.viewOption}/</pattern>
<view-id>/approved.xhtml</view-id>
<action>#{params.loadViewOption}</action>
</url-mapping>
If you want to try a more advanced URL-rewriting tool, also from OCPsoft, you can use "Rewrite" (http://ocpsoft.com/rewrite/), which is a Java-based URL-rewriting tool, but does not have as much integration with JSF.
PrettyFaces 4 will be based on rewrite as a core, at which point, all of the features you currently use will also be available with the ability to do something more like this, which is what you want if I am not mistaken:
.addRule(Join.path("/questions/approved/{viewOption}").to("/approved.xhtml")
.where("viewOption")
.matches("[^/]+/?")
.transformedBy(TrailingSlash.append())
.transformedBy(To.upperCase())
You would need to create your own transformers because they haven't been defined in the library yet, but that's the general idea. It's much more powerful than what's currently possible with PrettyFaces, but does not provide the same JSF navigation integration, and is a little trickier to configure.
I hope this helps,
~Lincoln
I have a web-app built with GWT, Request Factory and Places/Activities. I'm curious whether history tokens I use are persistent or not. The task is basically just about having URLs that define exact places of my web-app (read as - "files/folders structure"). So, what I need is urls like http://localhost/MyModule.html#uirwcynoerictyeroituwcyoi that would still cause the same data to be displayed even a year later. Does history token guarantee that for some particular Place it would be always the same?
If no, what is solution here?
For each Place you can write your own PlaceTokenizer. So if you don`t change your PlaceTokenizer (or write them to handle legacy places), you can use the same urls as long as you like.
Take a look here: http://code.google.com/intl/de-DE/webtoolkit/doc/latest/DevGuideMvpActivitiesAndPlaces.html#Places
Using Restlets you can route URIs using a system based on the URI template specification. I want to be able to route URIs which match the following pattern
http://www.blah.com/something/...arbitrarily long path.../somethingelse/
So, the following two URIs would be matched and routed the same:
http://www.blah.com/something/a/b/c/d/somethingelse/
and:
http://www.blah.com/something/z/y/x/w/v/somethingelse/
How can I achieve this using Restlets?
Cheers,
Pete
The most common way to set up routes is with a Router, like so:
router.attach("/path/to/resource", MyResource.class);
'attach' returns a Route, which has the method setMatchingMode, so you can do this:
router.attach("/path/to/resource", MyResource.class).setMatchingMode(Template.MODE_STARTS_WITH);
This sets the route to match any URL which starts with the supplied pattern.
I hope that's sufficient for your needs. I'm not aware of any built-in way to match URLs with a particular prefix and a particular suffix. But if that's specifically what you need, you could probably implement your own subclass of Template, Route, etc (I'm not sure which would be needed.)
I'm pretty sure that regex-based routing has been discussed on the Restlet mailing list; you may want to search there.