Best Practices for Designing Modern API

Introduction

REST API best practices help you develop a standard resource that your developers can use to consume your data and services. Even if you are not designing your API for the public, following the best design guidelines standardizes your application making its maintenance easier in the future. The majority of web players like Google, Facebook, Twitter, and Bigcommerce have public APIs. Unfortunately, each of these companies uses a different format. So, if you are starting as a developer, you might wonder whether there is a standard format for creating APIs bearing in mind that such big companies are following their conventions.

Luckily, there are some industry’s best standard API design guidelines that you can follow as detailed in this article.

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.

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

Here are a few points that you must keep in mind before creating your resources.

Use Nouns Instead of Verbs

A noun is a name of a thing while a verb is a 'doing word'. 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 Plural Nouns

Developers can have a hard time trying to consume an API that has both the singular and plural forms. For example, 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 misleading. Just use the plural form even when returning a single resource.

Differentiate 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 actions that can take place in that endpoint using HTTP verbs, such as 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.

  • POST: Creates new records.
  • GET: Retrieves records.
  • PUT Updates records.
  • DELETE removes resources.

Accept Resource IDs in API Endpoints

Resource IDs are important when your API consumers want to retrieve, update, or delete a single record. For instance, a sample URL like www.example.com/api/v1/customers/21 should retrieve a customer associated with ID # 21 when called using a GET HTTP verb. A delete request with the same URL deletes the associated customer customer.

Generate Resource IDs Internally in a POST Request

Generate the resource ID internally in a post request. Don't ask your API consumers to supply it in the POST payload. This can lead to all sorts of problems including skipped IDs, non-standard formats, and more.

Sample JSON API response with an ID Returned

JSON
{ 
    "id": "143562", 
    "name": "John Doe" 
}

Filtering, Sorting, and Paging in a Rest Application

Filtering

Your API should handle filtering when consumers want to return only a few records. Filtering is possible using the GET parameters that are embedded in the URL. For instance to retrieve all the products in a specific category, one might use the following URL format.

https://www.example.com/api/v1/products?category_id=4

Sorting

The need for arranging records from an API endpoint 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 displays the opposite on a report. To achieve all these, allow the developers to include the sort parameter when requesting a resource.

For instance, the following URL displays all products arranged in ascending order:

http://www.example.com/api/v1/products?sort=product_name

Also, the records can be arranged in descending order by prefixing the sort field with -.

https://www.example.com/api/v1/products?sort=-product_name

Pagination

A resource returning many records should allow pagination otherwise it might crash your API server. Different REST paging best practices exist but the common one uses a page parameter on the URL as shown below:

http://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 returned in a meta object at the end of the json document.

JSON
{
...
   "meta":{
      "page_number":5,
      "page_size":20,
      "total_record_count":521
   }
}

This way, developers can calculate 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, or shipped`.

Including the information on the orders table will bloat your database. To avoid the problem, you should create a different table with all the order statuses and assign IDs for the same. For instance:

  • unpaid: 0
  • paid: 1,
  • shipped: 2

After doing 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.

JSON
{

    "order_id": 5,
    "status_id": 2,
    "status_name": "shipped",
}

REST API Response Format

Json is 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.

Sample JSON response:

JSON
{
    "data" :{
      "sample" : "sampledata"
    },
    "meta" :{
      "sample2" : "sampledata"
    },

}

Sample JSON response with errors:

JSON
{
"errors" : {
    "sample3" : "sampledata"
  }
}

Field Names Casing

You can use camelCase or snake_case in field names but snake case is easier to read.

Examples of cases used in rest api fields:

  • camelCase: productName, categoryName
  • snake_case: product_name, category_name

Follow API Guidelines for HTTP Status codes

Always include the HTTP status header on every REST response:

  • 200 Ok: Returned on a successful GET, POST, PUT, DELETE or POST action.
  • 201 Created: Indicates that a new resource is created, such as a new customer.
  • 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 to display responses such as successful deletion.
  • 400 Bad Request: Indicates the request is malformed, such as when you send a payload with validation errors.
  • 401 Unauthorized: Means that the API users couldn’t be authenticated on the server.
  • 403 Forbidden: Restricts the API user from accessing restricted resources.
  • 404 Not Found: Returned if a resource is not found or when a user requests 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 with rate-limiting to avoid dos(Denial of Service) attack.

Version your API

An API version number, such as v1, v2, or v3 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 you release a new version. Don't replace the previous version's files with the new release since these will break the developer's code.

Use 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 and this 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 what the different API users can access.

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

Conclusion

The API interface design principles in this guide will assist you craft better APIs that follow the standard specifications. Remember upgrading your API in the future can be a painful process and conforming to the industry's best RESET web service guidelines will save you 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 REST API Design Readings

  • Databases
  • Webservers
  • PHP
  • API
  • Python
  • VPS Guides
  • Network
  • AI
  • Node.js