Rest API Best Practices for Beginners

In this guide, I am going to talk about REST API best practices that you can follow to craft a standard API that your developers can use to consume your data and services without any trouble.

Even if you are not designing your API for the public, following the best API design guidelines standardizes your application hence making it easier to maintain  in the future.

The majority of web players  like Google, Facebook, Twitter and Bigcommerce have public API’s. Unfortunately, each of these companies uses a different format.

So, if you are starting out as a developer, you might wonder whether there is standard format of creating APIs bearing in mind that such big companies are following their own conventions.

Luckily, there are industry’s best standard API design guidelines that you can follow and I am going to talk about them here.

Separate your REST API interface into Logical Resources

Creating an API is both an art and a science. Use your software architectural skills to make a rest API interface that is easy for developers to understand. Creating logical resources is not hard.

You need to consider all possible endpoints that your API will expose to the public or your in-house software application. For instance, when designing my API endpoints I start with offices, followed by system roles, e.t.c.  The same case applies to your application.

To put this into perspective an API for an online shop can have the following endpoints:

  • products_categories – www.example.com/api/v1/products_categories
  • products – www.example.com/api/v1/products
  • customers – www.example.com/api/v1/customers
  • sales_orders – www.example.com/api/v1/sales_orders

API Interface Design Principles

When I first designed my API’s, I used all kind of names on the endpoints because I wasn’t following any design guidelines. However, here are a few points that you must keep in mind before creating your resources.

Use Nouns Instead of Verbs

A noun is a word used to identify something while a verb is a “doing word” that describes an action. For instance, if you are creating a products resource, you shouldn’t use an endpoint like “createproduct” or “editproduct”. Instead use an endpoint like “products”.

Use Plurals on your API Endpoints

Developers can have a hard time trying to consume an API that has both the singular and plural forms. E.g. a poorly designed API for retrieving customers can have different endpoints like www.example.com/api/v1/customers and www.example.com/api/v1/customer.

The former can be used to create, delete or retrieve a single customer while the latter can return all customers. Such a design is completely confusing. Just use the plural form even when your api is returning a single resource.

Differentiate API Actions Using HTTP verbs

As mentioned above, a good API should use the plural form of the noun e.g. www.example.com/api/v1/customers. However, you can differentiate the different kind of actions on that endpoint by using http verbs: POST, GET, PUT and DELETE.

So any call to your API will perform the appropriate action and take care of CRUD (Create, Read, Update, and Delete) operations. The Post http verb will be used for creating new records, GET will retrieve  records, PUT will update the records while DELETE will remove an existing record from database.

Your API Endpoints Should Accept Resource Id’s

Resource Id’s are very important when your API consumers want to retrieve, update or delete a single record. E.g. a sample URL like www.example.com/api/v1/customers/21 should be able to retrieve a customer with Id # 21 when called using a GET http verb. A delete request with the same URL will delete the customer with that id.

Generate Resource Ids Internally During POST Requests

Generate the resource id internally in a post request. Don’t ask your API consumer to supply it on the POST payload. This can lead to all sort of problems including skipped id’s, non standard formats (e.g. in case of bank application) e.t.c

Sample json API response with an id returned

{

"id": "143562",

"name": "John Doe"

}

REST API Filtering, Sorting and Paging 

Filtering: Your API should handle filtering when consumers want to return only a few records. Filtering is possible using the GET parameters  embedded on the URL. For instance to retrieve all the products in a specific category, one might use an URL format like www.example.com/api/v1/products?Category_Id=4.

Sorting: The need of arranging and separating records from an API  is inevitable. A good example is when an API consumer wants to display the most recent records at the top of a list view but display the opposite on a report.

To achieve such a function, allow the developers to include the sort parameters when requesting a resource e.g. the url www.example.com/api/v1/products?sort=product_name will display all products arranged in ascending order  by the product_name field. Also the records can be arranged in a descending order by prefixing the sort field by a “-” minus/negative sign e.g. www.example.com/api/v1/products?sort=-product_name

Pagination: A resource returning a lot of records should allow paging otherwise it might crash your API server. Different rest paging best practices exist but the common one uses a page parameter on the URL E.g. www.example.com/api/v1/products?page=4.

Also, the API consumer should know the total number of pages and count of records expected in a resource. Pagination information should be included in a meta member at the end of the json document.

meta : {
"page": 5,
"per_page": 20,
"total_pages": 27,
"count": 521
}

This way, developers can display the total number of pages expected from a resource without errors.

Spell out Magic Numbers

Using magic numbers in a database environment is inevitable due to optimization. For instance, if you are designing an e-commerce api, the possible statuses of the order can be ‘paid’,’unpaid’,’shipped’

Including the information on the orders table will bloat your database. To avoid the problem, you create a different table with all the resources and assign ids for the same e.g. unpaid -0, paid -1, shipped -2.

Once you do that, you should remember to spell out the magic numbers when returning the response to the consumer as shown below. Otherwise, they will have to make two round trips to your API server to get the representation of each magic number.

{

"order_id": 5,

"status_id": 2,

"status_name": "shipped",

}

REST API Response Formats

Json has become the standard format of REST API responses and XML is quickly becoming deprecated. Json is lighter and easy to serialize or deserialize. The Json API response should contain 3 mandatory top level members including data, errors and meta. However, data and errors cannot co-exist in the same document.

Here is a sample json response with all elements:

{

"data" :[

{"product_id" : 1,"product_name" : "Coast Sheena Maxi Dress"},

{"product_id" : 2,"product_name" : "Reila Mini Dress"},

{"product_id" : 3,"product_name" : "Siffon Midi Yellow"}

]
meta : 
{ "page": 1, "per_page": 3, "total_pages": 4, "count": 12 }


}

Json API Response with Errors

Returning a single error in a REST api response is recommended as it allows the client to deal with the error properly. Always include an error code and the details. Title is optional.

{

"errors" :{
"code" : 400,
"title" : "Validation Failed",
"detail" : "First_Name is a required."
}

}

Field Name Casing in Json REST APIs

You can use camelCase or snake_case in field names but most experts agree that snake case is easier to read. When I first show an API provider using camelCase, I thought their developers were making typing errors and I can attest that camelCase does not look any good!

Examples of Cases Used in REST API Fields

  • camelCase:  e.g. productName, categoryName
  • snake_case :  e.g. product_name, category_name or Product_Name, Category_Name

Rest API Guidelines on HTTP Status Codes

Always Include the status header on every rest response in regards to the following.

  • 200 Ok – should be returned on a successful GET, POST, PUT, DELETE or POST action
  • 201 Created – should be returned to indicate that a new resource is created e.g. a new customers
  • 202 Accepted – indicates that a request has been successfully received but it’s still waiting processing. Common in the finance industry.
  • 204 No Content – used upon a successful deletion
  • 400 Bad Request – The request is malformed e.g. when you send a payload with validation errors
  • 401 Unauthorized – means that the api users couldn’t be authenticated on the server
  • 403 Forbidden – useful to restrict the api user from accessing restricted resources
  • 404 Not Found – return this status if an item is not found or when a user request a resource that does not exist.
  • 405 Method Not Allowed – returned when the http method is not allowed on a resource. For instance, if a user sends a delete request to the users’’ endpoint, the response should be returned.
  • 429 Too Many Requests – used alongside rate-limiting to avoid dos(Denial of Service) attack.
  • 500 Internal server error : Generated when there is a problem with the server e.g. due to failed database connection.

Versioning your REST API

An API version number (e.g. v1, v2, v3, e.t.c) should be included in the URL like www.example.com/api/v1 . A rule of thumb is to always support the previous version when you migrate to a new one.

 Increment the version number once your release a new version. Don’t replace the previous version’s files with the new release since these will break the developer’s code.

REST Web Services Security Best Practices

Use SSL everywhere and when a client requests data through the non-secure channel http, never redirect them to https but just reply with an error message.

SSL makes your API secure since your consumers could be accessing the resources from unsafe wifi-hotspots and cyber cafes which may lead to a man-in-the-middle attack.

Use strong hashing algorithms like bcrypt and avoid the less secure functions like md5 when storing passwords and authentication tokens.

Your API should also have a strong form of authentication. You can use Oath2 or Basic authentication. Remember to create strong authorization rules and use roles to differentiate the different categories that an API user can access.

Use rate limiting in the API resource to avoid users from abusing your service and block all IP addresses trying to brute-force passwords.

Conclusion

I hope the API interface design principles on this guide will assist you craft better API’s that follow the standard specifications.

Remember updating your API in the future can be a painful process and conforming to the industry’s best rest web service guidelines will save your time.

Although this is not an exhaustive list, it has covered the most common features every pragmatic restful design  of an API should consider.

Further readings

Ads by Google

One thought on “Rest API Best Practices for Beginners”

Leave a Reply

Your email address will not be published. Required fields are marked *