How to write a piece of art REST API

If a while back you only had to deal with writing an API only if you wanted your services to be integrable with third party apps, the situation is now quite different. With the growing trend of single page apps, the way we handle the backend has drastically changed. So, if you’re a backend developer, it’s almost certain that you’ll have to go RESTful at some point down the road. Here is what you should keep in mind.

Keep a uniformed interface

When building a RESTful API, this is the first thing you should focus on. The uniformed interface is the number one feature that distinguishes REST from other architectural styles.

The main point here is to have a resource for every relevant segment of the API, identify those resources with URIs and always return consistent resource representation. The resource identifiers should always go in the URL, as opposed to the query string. Leave the query string for filtering.

Keep clear URL hierarchy

Leverage the hierarchical nature of the URLs to extend the clarity of your API.

/users/223/addresses

The URL above can’t be misunderstood — you know exactly what resource the request works with at the moment you see it.

Keep consistency in resource names and URIs>

  1. Always use nouns as resource names to improve clarity. Unlike SOAP APIs where the URLs tend to be very descriptive, REST APIs use a combination of a resource and a HTTP verb to describe the action. So, instead of
    /user_list

    to indicate that the request retrieves a list of user records, go with

    GET /users
  2. Use plural for your URL segments to keep your URIs consistent across all HTTP methods. This would mean that to get the list of users, you would go with
    /users

    and to get the user details for a specific user

    /users/223
  3. Use lowercase letters for the URLs, separating the words with underscores (‘_’) or hyphens (‘-’).

Keep URLs as short as possible

You aim to provide as much clarity through the resource URL as possible, but you should be careful not to end up with too long URLs. Just stick to the guidelines above and you should have short URLs that are clear and consistent.

Use HTTP verbs

Now that you have the resources well defined with nouns, you should provide some meaning to the requests using HTTP verbs. The four most commonly used are:

  1. GET — request a collection of resources, or request the details for a specific resource by passing its identifier.
  2. PUT — update a resource by providing its identifier, or create a new one when its identifier is determined upfront.
  3. DELETE — delete a resource by providing its unique identifier.
  4. POST — create a new resource. Can also be used as a general verb when an action doesn’t fit any of the other categories.

Back to our User resource, these are the possible requests we would have:

GET /users
GET /users/223
PUT /users/223
POST /users
DELETE /users/223

Return meaningful responses

Whether it’s a success or an error, the client that depends on your API will need meaningful and consistent responses to know how to proceed.

Use HTTP response codes to indicate the status of the request. Return a 404 if the record was not found, or a 401 if the user is unauthorized to proceed with the selected operation. When the request was successfully executed, don’t jump in with the general 200. Return a 201 if a new record was created or a 204 if the operation was successful, but no content is returned (usually the case of PUT and DELETE methods).

Make sure the client can understand exactly what the status of the operation is, how to read the response and how to proceed further in case of an error. Check the official HTTP status code definitions for better insight on what you need in different scenarios.

Another thing you should keep in mind is to always provide information about record limits and pagination details when a collection of resources is requested.

{
    "metadata": {
        "resultset": {
            "count": 1225,
            "offset": 100,
            "limit": 25
        }
    },
    "results": []
}

Go stateless

The application state is the data the server needs to fulfill a request. Unlike the resource state, which is constant no matter who requested it, the application state depends on the client and could vary between requests. The best example for it is authentication data — it depends on the client and the server needs it to check if the client is authorized to make the request.

RESTful APIs are always stateless, which means the state data has to be sent with every request. So, handling authentication goes completely on the client’s side and the server gets the state data in each request. This can slightly affect the network performance, but it improves the visibility, scalability and reliability.

So, what happens here? The state data is sent in each request as part of the URL, query string parameters, body, or headers. That means that a look at a single request can define its full nature, so you don’t have to research beyond that when monitoring a request. Plus, having the data in each request makes it easier to recover from partial failures. So, we have better visibility and reliability.

Since we handle the state completely on the client’s side, the server doesn’t need to manage resource usage across requests, so its implementation is very simplified. And not having to store the state between requests makes it possible to quickly free resources. This results in a more scalable server.

To keep statelessness and securely store and transfer data between client and server when implementing authentication, consider using JSON Web Token (JWT). It is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.

JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. The…jwt.io

Version your API

Considering the pace at which the tech is moving forward, it’s very likely that your processes or resources will change over time. So, changing the API at some point is inevitable.

Versioning your API right from the start would add to its consistency and would make the whole upgrade process easier for you and the developers who will use it. The best approach to handle versioning is to add the API version to the URL. So, the full URL for retrieving a collection of users would be:

yourdomain.com/api/v1/users

Write the docs

This can not be stressed out enough. Writing documentation is not something we look forward to as developers, but it’s essential for everyone who will be using your API. Your documentation should properly describe the classes and methods of your API and include sample code that shows how to use them.

There are tools you can use to generate a nice looking documentation from your source code comments. You can try apiDoc, it supports multiple languages and it’s pretty straightforward to get started with.

I would love to hear from you. Do you have any tips that we should consider when creating a REST API?

Katerina Trajchevska
CEO and Senior Software Engineer