RESTful API Design Principles
Updated July 2024:
What is RESTful API?
An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.
REST is acronym for REpresentational State Transfer. It is architectural style for distributed hypermedia systems and was first presented by Roy Fielding in 2000.Like any other architectural style, REST also does have its own 6 guiding constraints which must be satisfied if an interface needs to be referred as RESTful. These principles are listed below.
Guiding Principles of REST
1. Client–server – By separating the user interface concerns from the data storage concerns, we improve the portability of the user interface across multiple platforms and improve scalability by simplifying the server components.
2. Stateless – Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.
3. Cacheable – Cache constraints require that the data within a response to a request be implicitly or explicitly labelled as cacheable or non-cacheable. If a response is cacheable, then a client cache is given the right to reuse that response data for later, equivalent requests.
4. Uniform interface – By applying the software engineering principle of generality to the component interface, the overall system architecture is simplified and the visibility of interactions is improved. In order to obtain a uniform interface, multiple architectural constraints are needed to guide the behaviour of components. REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.
5. Layered system – The layered system style allows an architecture to be composed of hierarchical layers by constraining component behaviour such that each component cannot “see” beyond the immediate layer with which they are interacting.
6. Code on demand (optional) – REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts. This simplifies clients by reducing the number of features required to be pre-implemented.
Important Elements of REST API
Resource
One of the important element of REST is a resource. Any information that can be named can be a resource: a document or image, a service, a collection of other resources, a non-virtual object (e.g. a person), and so on. REST uses a resource identifier to identify the particular resource involved in an interaction between components.
Further, resource representations shall be self-descriptive: the client does not need to know if a resource is employee or device. It should act on the basis of media-type associated with the resource.
Resource Methods
Another important thing associated with REST is resource methods to be used to perform the desired transition.
There is no standard recommendation around which method to be used in which condition. All that is emphasized is that it should be uniform interface. If you decide HTTP POST will be used for updating a resource – rather than most people recommend HTTP PUT – it’s alright and application interface will be RESTful.
Ideally, everything that is needed to change the resource state shall be part of API response for that resource – including methods and in what state they will leave the representation.
Design Guide for HTTP API
The main goal while designing RESTful API’s is to maintain consistency and focus on business logic.
Following are the recommendations to follow while designing the API’s
A HTTP request and response will be made to address a particular resource or collection.
HTTP request is made up of the following things
· The endpoint
· The method
· The headers
· The data (or body)
Endpoint:
The endpoint (or route) is the URL you request for
e.g.: https://api.twitter.com
The path determines the resource you’re requesting for. It points to the particular resource you are looking for. To understand what paths are available to you, you need to look through the API documentation.
The final part of an endpoint is query parameters. They always begin with a question mark (?). Each parameter pair is then separated with an ampersand (&), like this:
e.g. ?query1=value1&query2=value2
JSON (JavaScript Object Notation) a common format for sending and requesting data through a REST API.
A JSON object looks like a JavaScript Object. In JSON, each property and value must be wrapped with double quotation marks, like this:
{
“property1” : “value1”,
“property2” : “value2”
}
The method is the type of request you send to the server. You can choose from these four types below:
GET : This request is used to get a resource from a server
POST : This request is used to create a new resource on a server
PUT: This request is used to update a resource entirely on a server.
PATCH: This request is used to partially update a resource on a server
DELETE: This request is used to delete a resource from a server.
Headers
Headers are used to provide information to both the client and server.
HTTP Headers are property-value pairs that are separated by a colon. The example below shows a header that tells the server to expect JSON content.
“Content-Type: application/json”
Data
The data (sometimes called “body” or “message”) contains information you want to be sent to the server. This option is only used with POST, PUT, PATCH or DELETE requests.
Authentication
Authentication prevents others from impersonating you. Developers put measures in place to ensure you perform actions only when you’re authorized to do.
Authentication method generally used in REST API’s is Secret token method like oAuth
HTTP Status Codes And Error Messages:
Some of the messages you’ve received earlier, like “Requires authentication” and “Problems parsing JSON” are error messages. They only appear when something is wrong with your request. HTTP status codes let you tell the status of the response quickly. The range from 100+ to 500+. In general, the numbers follow the following rules:
1. 200+ means the request has succeeded.
2. 300+ means the request is redirected to another URL
3. 400+ means an error that originates from the client has occurred
4. 500+ means an error that originates from the server has occurred
API Versions
Developers update their APIs from time to time. Sometimes, the API can change so much that the developer decides to upgrade their API to another version. If this happens, and your application breaks, it’s usually because you’ve written code for an older API, but your request points to the newer API.
You can request for a specific API version in two ways. Which way you choose depends on how the API is written.
These two ways are:
1. Directly in the endpoint.Version is mentioned in the endpoint itself
2. In a request header.Version is mentioned in the request header
e.g. https://api.github.com -H Accept: application/vnd.github.v3+json
RESTful API Documentation
API documentation is done based on swagger or stoplight specifications.
BEST Practices of REST API Design
Though REST supports different data formats, but JSON is preferable and widely used.
Use nouns instead of verbs.
Correct way
GET /movies/Home Alone
DELETE /movies/Home Alone
POST /movies
PUT /movies/Home Alone
PATCH /movies/Home Alone
-vs-
Incorrect way
GET /addMoviesMadagascar (by the way, GET should be only used to READ data and never to change its state in any way)
GET /DeleteMovies/123
POST /DeleteAllMovies
Collection Names should be plural nouns.
Good Error Handling should be done in API development. Use appropriate HTTP error codes with a meaningful message to the user which could help him debug the errors.
Use query parameters to use filtering, sorting or paging.
Version your API.
Document your API.
References: