Quantcast
Channel: Mobile App Development & Design Company – Snyxius
Viewing all articles
Browse latest Browse all 167

21 Best Practices for designing and launching a RESTful API

$
0
0

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”

2. Provide Links for Navigating through your API (HATEOAS)

Hypermedia athe Engine oApplication State is a principle that hypertext links should be used to create a better navigation through the API.

A hypermedia-driven site provides information to navigate the site’s REST interfaces dynamically by including hypermedia links with the responses.

A HATEOAS-based response would look like this:

{

    "name": "Alice",

    "links": [ {

        "rel": "self",

        "href": "http://localhost:8080/customer/1"

    } ]

}

This response not only has the person’s name, but includes the self-linking URL where that person is located.

  • rel means relationship. In this case, it’s a self-referencing hyperlink. For example, an order might have a “rel”:”customer” relationship, linking the order to its customer.
  • href is a complete URL that uniquely defines the resource.

3. Less Is More: Always Paginate Your Results

Most modern API have come across this functionalities of setting the parameter in resources because we can’t return hundred or thousand of records when it come to fast and responsive UIs.

For that reason we need pagination mechanism to make sure the responses are easier to handle.

Pagination would look like this:

{             
 “start”: 1,
 “count”: 20,
 “totalCount”: 100,
 “totalPages”: 5,
 “links”: [
 {
 “href”: “https: //<url>/offset=40&limit=20”,
 “rel”: “next”
 },
 {
 “href”: “https: //<url>/offset=0&limit=20”,
 “rel”: “previous”
 }
 ]
 }

4. Set the parameter for resources

/employees?offset=30&limit=15       #returns the employees 30 to 45

If the client omits the parameter you should use defaults. Don’t return all resources. A good default is offset=0 and limit=10. If the retrieval is more expensive you should decrease the limit.

/employees       #returns the employees 0 to 10

Moreover, if you use pagination, a client needs to know the total number of resources.

Example

Request: GET/employees

Response:

 

{

  "offset": 0,

  "limit": 10,

  "total": 3465,

  "employees": [

    ...

  ]
}

5. Handling ERROR JSON

In an API handling error is important and it requires careful planning.

And it’s highly recommended that always return the error message in its own set of field.

A JSON error body should provide a few things for the developer – a useful error message, a unique error code (that can be looked up for more details in the docs) and possibly a detailed description.

A good error message response might look something like this:

{
“code”: 1234,
“message” : “Something bad happened :(“,
“description” : “More details about the error here”
}

6. Use sub-resources for relations

Sub resources are used to link one resource with another, so use sub resources to represent the relation.

GET /groups/{group id}/members Returns a list of members in group with given id
GET/groups/{groupid}/members/{member id} Returns user with given user id for given group id

Example

GET /cars/711/drivers/ Returns a list of drivers for car 711

GET /cars/711/drivers/4 Returns driver #4 for car 711

7. Use Date/Time Serialization in HTTP Headers

The HTTP utilizes a different format for HTTP headers, which is Specified in RFC 822 which was updated by RFC 1123, that format includes various date, time and date-time formats.

It is recommended that you should always use a time-stamp format which will look like this in your request headers:

Sun, 06 Nov 1994 08:49:37 GMT

Unfortunately, it doesn’t account for a millisecond or decimal fraction of a second in its format.

8. Use the custom HTTP Header X-HTTP-Method

As you know some proxies only support POST and GET method, and we know that it’s difficult to support API with this limitation.

So, to override this POST and GET method, use the custom HTTP Header X-HTTP-METHOD-Override.

9. Create Fine-Grained Resources

When starting out, it’s much easier to create APIs that mimic the underlying application domain or database architecture of your system.

Eventually, you’ll want aggregate services—services that utilize multiple underlying resources to reduce chattiness.

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

restful-api-best-practices-example

  • 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

restful-api-best-practices-example-1

  • 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.

Typically Client will convert the JSON response to a JavaScript object (bycalling var person = JSON.parse(response) ) and call its attributes.

Therefore, it’s a good idea to stick to the JavaScript convention which makes the JavaScript code more readable and intuitive.

17. Use verb for non-resources

Sometimes a response to an API call doesn’t involve resources (like calculate, translate or convert).

Example:

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.

 

The post 21 Best Practices for designing and launching a RESTful API appeared first on  - Snyxius.


Viewing all articles
Browse latest Browse all 167

Trending Articles