Design REST APIs Effectively

I have been building APIs for a quite a long time but i am not an expert(just being honest here). I am going to share my experience of REST APIs with you, if you find it good then you can apply it to your API design process.

Well, this tutorial is not aimed at any framework, you can apply the theory mentioned in this tutorial in any language or framework.

The first thing in my opinion the one should do while designing API is planning :)

Let's plan API endpoints for our application.

WTF, what application are you talking about?

Oh, sorry, we are going to create a contacts book type app. In which a user can register and can save contacts in his/her account. So, let's start then.

Planning

Right now i am thinking of everything our API will need to handle. Initially will be list of CRUD endpoints for our resources.

WTF is a resource now?

A resource is an object with a type, associated data, relationships to other resources, and a set of methods that operate on it.

In English and with example, please!

Well, for this contacts app we will have two resources:

  • Users
  • Contacts

So if i have Users and Contacts resource in mind, i need to list out with main points what it will do:

Users

  • Create
  • (R)ead
  • (U)pdate
  • (D)elete
  • List (active, suspended)
  • Image

Contacts

  • Create
  • Read
  • Update
  • Delete
  • List
  • Favorite
  • Image

Deciding Endpoints

There are different approaches for naming conventions and some approaches have fewer cons than others. I am going with the one which i found to be most useful.

The basic concept in naming endpoints is keep verbs out of URLs and Use HTTP verbs to operate on the resources.

what do you mean by "Keep verbs out of urls", han?

Bhai dekh(Listen brother - in hindi), take our user resource, for creating new user, endpoint should be
POST '/Users' but not /createNewUser

POST is an HTTP verb. We will make a post request on endpoint /Users with data required to create an account.

Available HTTP Verbs Are:

  • GET (Get Resource)
  • POST (Create)
  • DELETE
  • PUT (Edit)
  • PATCH (Partial Edit)

Get User Resources Endpoint

  • GET /users - Get paginated list of users sorted in some default order
  • GET /users/SOMEUNIQUEIDENTIFIER - An entity of user
  • GET /users/SOMEUNIQUEIDENTIFIER/contacts - Get contacts of a particular user
  • GET /users/A,B,C - Multiple users for specific unique identifiers.

We can apply same to Contacts resource too.

Create User Resources Endpoint

A post request on user endpoint with required data should create a resource

  • POST /users
  • POST /users/SOMEUNIQUEIDENTIFIER/contacts - This should create a new contact and link it with a specific user

What about update, eh?

The HTTP methods PATCH can be used to update partial resources. For instance, when you only need to update one field of the resource while PUT is for updating all the fields of the resources, which cumbersome and utilizes more bandwidth.

However not all web servers (and forget about clients) support PATCH so people have been supporting both partial updates with POST and PATCH:

POST /users/SOME_UNIQUE_IDENTIFIER/contacts/SOME_UNIQUE_IDENTIFIER_FOR_CONTACTS  
{favorite: 1}

In above code what we did is that we made a POST request with data {favorite:1} and it should set that contact to favorite.

Responses

A server MUST respond to a successful request to fetch an individual resource or resource collection.Now there are a lot of formats for returning data but i like JSONapi.org's format the most.

Status Codes and error messages

2xx codes are used to show that whatever client tried to do was successful.

4xx codes are used to tell the client that a fault has taken place on their side.

5xx codes tell the client something happened on the server and their request by itself was perfectly valid. The client can continue and try again with the request without modification.

  • 200 - Generic everything is OK
  • 201 - Created something OK
  • 202 - Accepted but is being processed asynchronously
  • 400 - Bad Request
  • 401 - Unauthorized
  • 403 - The current user is forbidden from accessing this data
  • 404 - That URL is not a valid route, or the item resource does not exist
  • 410 - Data has been deleted, deactivated, suspended, etc
  • 405 - Method Not Allowed
  • 500 - Something unexpected happened and it is the APIs fault
  • 503 - API is not here right now, please try again later

While throwing error messages our api should give the client as much information as possible about the error.

{
   "status": 400,
   "code": 4000,
   "message": "Email is not valid"
}
  • status holds HTTP error status code, so that developer can see it without having to check http headers.
  • code is an internal codes specific to the API
  • message is the description of the error

So this is just a brief introduction to the designing principal of a good rest api.

Following are some of the tools which you will find helpful while working on your api

  • Postman - A Web REST client that allows you to enter and monitor HTTP requests and responses.
  • Faker - It is a PHP library that generates fake data for you
  • JSON Data Generator
comments powered by Disqus