21 Best Practices for designing and launching a RESTful API

NOTE: This article is part two “21 Best practices for designing and launching a restful API”. In part one, you learned to develop a RESTful API and some of the best practices related to it.

In part two, our main goal is to provide a road-map for designing and launching a REST API. We would recommend you to go through the first part, Guide to REST API Best Practices, before you proceed.

Welcome to the part two.

1. Use plural nouns

Some of you might already know about it. But what to do when using plural for single instance of resource? If you want to keep your resources name more natural then always use plural.

Don’t get mix up with singular and plural noun.

For example use:

/t-shirts instead of /t-shirt

Thus, we recommend the plural form for 2 types of resources:

Resource collections: /v1/t-shirts

Resource instances: /v1/t-shirts/007

As an example, for the creation of a user we will consider that POST /v1/t-shirts is the call of the create action on the users collection. Likewise, GET /v1/t-shirts/007 to retrieve a user can be understood as “I want t-shirt 007 in the t-shirts collection”

But it’s much easier to create larger resources later from individual resources than it is to create fine-grained or individual resources from larger aggregates.

Make it easy on yourself and start with small, easily defined resources, providing CRUD functionality on those. You can create those use-case-oriented, chattiness-reducing resources later.

10. Consider connectedness

One of the principles of API is connectedness—via hypermedia links.

While services are still useful without them, APIs become more self-descriptive when links are returned in the response.

At the very least, a ‘self’ reference informs clients how the data was or can be retrieved.

Additionally, utilize the Location header to contain a link on resource creation via POST. For collections returned in a response that support pagination, ‘first’, ‘last’, ‘next’ and ‘prev’ links at a minimum are very helpful.

11. Result filtering and sorting

Another consideration for affecting results is the act of filtering data and/or ordering it on the server, retrieving a subset of data and/or in a specified order.

These concepts work in conjunction with pagination and results-limiting and utilize query-string parameters, filter and sort respectively, to do their magic.

Again, filtering and sorting are complex operations and don’t need to be supported by default on all resources. Document those resources that offer filtering and sorting.

Filtering

Filtering is defined as reducing the number of results returned by specifying some criteria that must be met on the data before it is returned.

Filtering can get quite complex if services support a complete set of comparison operators and complex criteria matching.

However, it is quite often acceptable to keep things sane by supporting a simple equality, ‘starts-with’ or contains comparison.

For example:

GET /groups?status=active – Returns a list of active groups

Sorting

Sorting is defined as determining the order in which items in a payload are returned from a service. In other words, the sort order of multiple items in a response payload.

For example,GET /groups?sort=status,-name – Returns list of groups in ascending order of status; Within the same status, groups returned will be sorted by name in descending order.

12. Use TLS/SSL for Transport Security

Thanks to internet your web API can access from anywhere, it is very easy to retrieve the username and password from a basic authentication.

To secure your web API authentication, all authentications should use SSL. OAuth2 requires the authorization server and access token credentials to use TLS.

Switching between HTTP and HTTPS introduces security weaknesses and best practice is to use TLS by default for all communication.

13. Rate limiting

If your API is success then thousands of users will integrate to your API, things can and will go wrong: Inexperienced developers will call you thousands of times per hour.

Then you should consider implementing rate limit early on.

By implementing rate limit to your API you can protect server from being overloaded and maintain high quality of service to clients.

At a minimum, include the following headers.

X-Rate-Limit-Limit- The number of allowed requests in the current period

X-Rate-Limit-Remaining – The number of remaining requests in the current period

X-Rate-Limit-Reset – The number of seconds left in the current period

14. Use PUT on element- URL for updating resources

The client sends a PUT request to the element URL /employee/21. The HTTP body of the request contains the updated attribute values (the new name “Bruce” of the employee 21).

The REST service updates the name of the employee with the ID 21 and confirms the changes with the HTTP status code 200

15. Use POST on collection-URL for creating a new resource

The client sends a POST request to the collection URL /employees. The HTTP body contains the attributes of the new resource “Harry Porter”.

The RESTFUL web service generates an ID for the new employee, creates the employee in its internal model and sends a response to the client.

This response contains a Location HTTP header that indicates the URL under which the created resource is accessible.

16. Use camelCase for Attribute names

To avoid the naming limitation, use CamelCase.

CamelCase is a naming convention in which a name is formed of multiple words that are joined together as a single word with the first letter of each of the multiple words capitalized so that each word that makes up the name can easily be read.

The camelCase will look like this:

{ "yearOfBirth": 1982 }

Reason behind using Camelcase

JavaScript convention read those JavaScript code which do not use Underscores for example (“year_of_birth”) or capitalize (“YearOfBirth”).

That RESTful web service will be consumed by a client written in JavaScript.

17. Use verb for non-resources

GET /translate?from=de_DE&to=en_US&text=Hallo
GET /calculate?para2=23&para2=43

In this case, your API doesn’t return any resources. Instead, you execute an operation and return the result to the client. Hence, you should use verbs instead of nouns in your URL to distinguish clearly the non-resource responses from the resource-related responses.

18. Use content-type header

As you know everyday new format are created and used, recently XML was the format choice of the web server, but then JSON came along.

So, to keep your API flexible and extendable for future, it is important that we should build API for future not for today.

By taking advantage of content-type header we can define the request format and in return we can send back the same format.

For example, if a user sends a request using text/xml, you could send back an XML response while another user could send an application/JSON request and you could reply with JSON.

By building this functionality into your API, you are able to adapt to these new format requests without impacting other users, or other aspects of your API.

This also means that you can stay on top of the technology curve without worrying about having to migrate users from one format to another, or from one API to another.

19. Use HAL when providing hyperlink

HAL is a simple format that gives a consistent and easy way to hyperlink between resources in your API.

Adopting HAL will make your API explorable, and its documentation easily discoverable from within the API itself. APIs that adopt HAL can be easily served and consumed using open source libraries available for most major programming languages.

20. Use varnish for caching HTTP reverse proxy

Varnish is an open source web accelerator that’s designed for high-performance content delivery. And it is a key to accelerate dynamic content, APIs and logic at the edge.

Varnish receives a request for customer content that is not already cached; it will reach out to the customer’s origin servers and fetch the item requested, then send it to the user who has requested it.

One of the key features of using Varnish Cache, in addition to its performance, is the flexibility of its configuration language, VCL.

VCL enables you to write policies on how incoming requests should be handled. In such a policy you can decide what content you want to serve, from where you want to get the content and how the request or response should be altered.

21. Aliases for common queries

To make the API experience more pleasant for the average consumer, consider packaging up sets of condition into easily accessible RESTful paths. For example, when querying for most active, recommended groups etc, we can have endpoint like

GET /groups/mostactive – Returns list of mostactive groups
Default values can be used for the sort parameters

Field selection

Field selection goes a long way in letting the API consumer minimize network traffic and speed up their own usage of the API.

Use a fields query parameter that takes a comma separated list of fields to include.GET /groups/?fields=id,name,owner,status&status=active&sort=-name

BONUS: Provide awesome documentation

This might be the hardest job.

But when exposing API to customer it is important to document all APIs. Documentation should minimum including description of API, error code, response code, sample success response and error response.

A single error or misunderstanding in documentation can drive developer’s nuts and make them hate your product.

So, be nice and provide all documentation to your developer that you would want to read.

There are lots of open source tools for awesome documentation like Swagger , ENUNCIATE and Miredot, which enable client and documentation systems to update at the same pace as the server.