API Design Best Practices: A deep-dive (2023)

by Success Ibekwe

.

Updated Sun Jun 18 2023

API Design Best Practices: A deep-dive (2023)

Web development is not complete if there is no smooth interaction between the client and the server side which makes API design best practices a necessary skill for developers.

The web is made up of two parts the frontend and the backend. The front-end is also known as the client side which involves what the user sees and interacts with when they visit a website or a web application.

On the other hand, the backend also known as the server-side is the aspect of the web application that is not visible to the user.

“It is responsible for data storage, management and also securing of the data received from the front-end and making sure it is available for the user when needed. When a user sends a request, the backend receives the information, processes it, and sends back a response.” Frontend vs backend.

In other, for this interaction to take place between the frontend and backend, we make use of an Application Programming Interface (API) to act as the middleman between them.

Just like every other concept in web development, there are always some best practices a developer needs to apply in other to build a web app that satisfies the user experience.

Also, REST API comes with its best practices that we can incorporate in other to help the backend receive data successfully and also for the frontend that is sending in the request not to face issues trying to do so.

So in this article, we are going to be looking at API design best practices that can be followed while designing a REST API.

The API design best practices in this article if followed will help you achieve the best APIs which help to serve and give your API consumer’s best experience.

Before we continue, let’s look at what REST API is.

What is a REST API?

REST stands for Representational State Transfer and was created by computer scientist Roy Fielding in 2000. While API stands for Application Programming Interface.

REST determines the structure of an API. There are specific rules developers need to commit to when designing an API.

When we combine the API with the REST design rule we say that it is a RESTful API

For an API to be considered RESTful, it must meet the following criteria:

  • The client-server architecture is managed through HTTP(s).

  • Cached data that simplifies the exchange of data between client and server.

  • Clients should be able to use hyperlinks to access all other actions they may take.

  • Client-server communication is stateless, which means no client information is kept between GET requests, and each request is separate and unrelated.

  • Client messages have sufficient data and instructions to be processed by clients.

  • A multi-tiered system that organizes servers of each type (responsible for security, load balancing)

So basically a REST API is simply creating a medium that involves a set of rules that gives different programs access to communicate with each other.

Now that we’ve known that REST API is simply a medium for two systems to communicate with each other.

Let’s dive then into the best practices in other to be able to create this smooth communication between the two systems.

API Design Best Practices.

Below are some of the industry standards and API design best practices you can use to develop your RESTful APIs.

REST API must Accept and Respond with JSON

JSON stands for JavaScript Object Notation. It is one of the formats like XML, and HTML in which API providers deliver data.

For some time now XML has been the format used by API providers to accept and respond to API requests.

However, as JavaScript is gaining popularity for application development, the use of JSON as a natively integrated data interchange format has increased because JSON is the native format for data in JavaScript applications.

Apart from it being a native format below are some of the reasons you should use JSON over XML

Less verbose

JSON is significantly less verbose than XML, it uses name/value pairs to separate pairs and also to separate the name from the value.

While XML uses opening and closing tags to separate the name from the value making it more verbose

XML representation
<Object><Name>Matt</Name><ID>183829</ID></Object>
JSON representation
Object {Name: Matt, ID: 183829};

The examples above clearly show that JSON uses lesser space by eliminating the need for opening and closing tags making it lighter than XML.

Less size

If we pass the same amount of information, JSON is faster to transmit and process the information because JSON is always smaller.

Subset of JavaScript

As we stated before JSON is a subset of JavaScript, which gives it a more advantage over XML because it fits seamlessly into JavaScript code.

Use Nouns Instead of Verbs in Endpoints

When naming resources in RESTful APIs It is important they are noun based so at each endpoint they signify what each is doing,

since all the HTTP methods used for carrying the basic Create, Read, Update, and Delete (CRUD) operations on these resources are already in their verb form

Some examples of HTTP methods include:

  • GET

  • POST

  • PUT

  • PATCH

  • DELETE

  • COPY

  • etc.

let’s take a look at some examples:

GET http://www.api.com/students this gets a list of students.

Here already the GET method is self-sufficient to let us know we are retrieving a collection of students’ data.

So doing something like this “ GET http://www.api.com/generateStudents” is not necessary.

Use Plural Nouns For Name Collections

When choosing between singular and plural nouns, we recommend you go for plural nouns instead.

It best describes what we are getting which in this case is the full collection of resources and not just one item out of the collection.

let’s see an example of the singular and plural nouns

Singular

GET /user

This doesn’t show that we are dealing with a collection of data, to the client this is just one user and this can be bad especially if we need to DELETE or update the post the client wouldn’t know if there is still some user remaining in the collection.

Plural

GET /users

This is a better approach, the client would know that we are dealing with the collection of data involving users and not just one user.

Use Status Codes in Error Handling:

“With Proper error handling, you can make your apps more robust which helps to create a better user experience and also helps to improve productivity.” Source: Error handling in Node.js

There are tons of built-in HTTP status codes available to properly handle errors and convey the result of a client’s request.

This is probably one of the best practices you need to keep in mind when designing your API. Also, returning a meaningful status code that correctly describes the type of error encountered is essential.

You wouldn’t want to be returning an error response with a status code that does not correspond to the error.

Let’s take a look at some of these status codes. The status codes are divided into five categories.

  • Informational— Communicates the state of the request. It ranges from 100-199.

  • Success— Communicate the Success of the request. It ranges from 200-299.

  • Redirection— Sends response about some additional action needed to complete a request. It ranges from 300-399.

  • Client Error— Sends error response that has to do with the client. It ranges from 400-499.

  • Server Error— Sends error response that has to do with the server. It ranges from 500-599.

Below is an example of the standard error messages in each error code.

Most Common Codes to Use For HTTP Requests

There are a few common codes that developers should start with. They are:

  • 200 — OK

  • 404 — Not found

  • 500 — Internal Server Error

Then you can build upon them if there is a need for a more detailed set of statuses, such as:

  • 201 — Created

  • 204 — No Content

  • 304 — Modified

  • 400 — Bad Request

  • 401 — Unauthorized

  • 403 — Forbidden

  • 501 — Not Implemented

This is not an exhaustive list of the status code, you can see the entire list at HTTP Status Codes

Use Resource Nesting

Nesting of resources also called sub-resources is important to maintain a hierarchical relationship between endpoints, and also show how different endpoints are interlinked.

For example, sites like Medium allow stories from different authors on their platform, having an endpoint such as https://medium.com/me/stories/public would make a valid nesting in this case.

Also, we might have comment resources on each of the posts, Therefore, to retrieve the comments, an endpoint like https://medium.com/posts/postId/comments would make sense.

This helps with readability. While applying resource nesting is a best practice it is also best practice to limit resource nesting to not more than three levels deep.

In the next section, we are going to explore pagination and how to paginate your API.

Use Filtering, Sorting, and Pagination to Retrieve the Data Requested

When your API endpoint is returning a lot of data like returning a list of users, then using filter, sort, and pagination is a good practice.

These help your API users retrieve the necessary data they require rather than loading the whole request, which can cause the database to be slow.

So a user can sort data by last modified date or by email.

For instance:

GET /users?sort_by=+email
//And
GET /users?sort_by=email

A user can also filter data like so:
https://myPortfolio.com/posts?tags=restapi

This endpoint will fetch any post that has a tag of REST API.

Use SSL for Security

Securing your API against malicious attacks is of utmost importance. Hackers may use automated scripts to attack your API server.

While there are other ways to secure your API, SSL can do the work perfectly fine.

SSL ( Secure Sockets Layer) is a standard technology used to secure an internet connection and keep any sensitive data that has been shared between the client and the server, making it difficult for internet hackers to read or modify the information that is been transferred.

For a beginner or want a single domain SSL, you need a hassle-free domain validation certificate aka DV SSL certificate that can be issued within a few minutes and offers the highest encryption.

You can also update your SSL to TLS(Transport Layer Security) if you wish it is an updated, more secure, version of SSL.

Well-compiled API Documentation

Documentation is important in REST API design. It is the medium in which you communicate the features of your API to your users helping them learn the best way to correctly use the API for maximum satisfaction.

While developing your API documentation ensure it is robust enough to walk a new user through your API design easily.

Some other relevant information that should be contained in your documentation includes the following:

  • Information on relevant endpoints of the API

  • examples showing requests for the endpoints

  • Information on how it can be implemented in several programming languages

  • Information on different errors with their status codes including their individual messages

Use Versioning Strategy

A versioning strategy allows clients to continue using the existing REST API and migrate their applications to the newer API when they are ready.

When there is a new version of your API, it is essential to implement the versioning strategy, because not every user would want to update their application instantly to the new version

To properly version our REST API there are basically four ways to follow and they are as follows:

Versioning through URI Path

This versioning format involves us including the version number in the URI path.

This is the strategy used by Facebook, Twitter, Airbnb, and many more. it uses the 1.2.3 format which stands for Major.Minor.Patch.

Versioning through query parameters

This involves including the version number as a query parameter.

Versioning through custom headers

This format of REST API versioning involves providing custom headers and attaching the version number as an attribute.

Versioning through content negotiation

Rather than versioning the entire REST API, the content negotiation approach allows the versioning of a single resource representation instead.

Conclusion

In this article, we went through the 9 API design best practices for REST API. These 9 practices include the following:

  • Using JSON to respond to the REST API.

  • Using Noun instead of Verbs in our REST API

  • Name REST API collections with a plural noun

  • Use status code in REST API error handling

  • Use resource nesting

  • Using filtering, sorting, and pagination to retrieve data requests.

  • Using SSL/TLS for security

  • creating well-compiled documentation for your REST API

  • Using versioning in updating the version of the REST API

With these practices, you should be able to successfully create a REST API that will satisfy your users.

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board

Backend Tips, Every week

Backend Tips, Every week