I recently started learning about REST and started developing a RESTful API. This has been a great learning experience because I’ve had to learn and apply new concepts and technologies. I’ve written a few points I reuse everyday as I develop this API and how I’ve needed to change the way I think about back-end services.
Resources vs. Services
The first thing I had to learn was how to think about the API. All of my experience has taught me to think about the web and server-side functionality as services. The client application or front end would make a request to an end point and the service would do a defined task. This model is very different for a REST API. The API is instead built around resources. For me, the simplest way to look at a resource is to consider a business object. Similar to a service oriented API, you build CRUD operations for your business objects. The differences are that the URI is more descriptive of the resource and the HTTP method describes the operation. I’ll get into how to use HTTP methods later but first here are some examples of resource related URI’s and how I use them.
- /api/products – Returns a collection of product resources
- /api/products/29 – Returns a specific product resource by ID
- /api/orders/9/products – Returns a collection of product resources related to a specific order resource with the given order ID
HTTP Methods
The POST and GET HTTP methods are the most commonly and widely used methods. In a RESTful API, four or five methods are regularly used, GET, POST, DELETE, PUT, and PATCH. Each method has a specific meaning to the server-side functionality.
GET
Use the GET method to look up, search, or filter a resource. When you want to retrieve a known resource you would make a request similar to the example above with the unique identifier. If you want to retrieve a collection of resources, say a subset of collection, then you could pass query string parameters to filter/search.
POST
Use the POST method to create resources. You send a new resource to the server to add it to the collection. The same request with an empty body will return empty instance of the resource. Lastly, after adding the resource, the server should return a 201 created status code and a location header with the URI of the resource as its value.
DELETE, PUT, and PATCH
The DELETE method does exactly that, it deletes a resource. Use the PUT method to replace all values of a resource but the PATCH method will update only part of the resource.
Related Posts
October 27, 2014
OAuth 2 Flows
January 22, 2014
TeamCity with SQL Server
January 22, 2013
Exploring PhantomJS
September 6, 2012
UpshotHelper Update
July 26, 2012
UpshotHelper
May 5, 2012