Working with RESTful API's
The year 2009 is said to be the year of the API. Not the dusty CORBA/SOAP/RMI kind but the new kid on the block, REST.
Many good people have written about what REST is. I will not pain you with yet an other explanation. In this post I will tell you how you can use a RESTful service as a programmer.
As a programmer you want to build reliant applications. You also know that users are strange beings. They do the most unfathomable things to your carefully crafted code. You cast exceptions and write exception handlers. RESTful services should provide you, the programmer, with just that information. When manipulating or creating a resource the remote service should tell you how that went in a response code. The bare minimum of response codes a service should sent back are:- 200, which tells you, the sender, the request was accepted and processed.
- 404, familiar from the web, the resource could not be found.
- 500, something went wrong on the receiving end.
I believe anything less is just broken and implementing only these three is bad practice in my honest opinion. So for the sake of it let’s pretend the webservice is well behaving and a bit more complete.
Context is king
It is important the remember that you are in a conversation with the service. Request and response are intimately linked. “43” isn’t much of an answer if you don’t know the question. So when a response code is 403 the service understood the request but refused to fulfill it. Why it refused to do so should be in the body of the response but it could be any number of reasons. What’s important is that the sender of the request understands that the request is not fulfilled and should act accordingly. How is should act is of no concert to the RESTful service.
When implementing a client for a RESTful service always be aware that the server could return response code XYZ. If you want special handling for a particular situation, for example a 404, match that response code. Treat 4xx and 5xx response codes as an exception and code handlers for that. An exception uncaught in your code will break your application. The same goes for uncaught 4xx and 5xx response codes.