Writing standard RESTful APIs & nodejs (practical example).

Chrisostom Kaweza
7 min readApr 20, 2019

--

rest-api

We had a serious discussion between front-end developers and back-end developers, on what the best way for writing standard web APIs is. The main goal was to come up with a standard, easy to use and predictable system for creating and consuming APIs.

After much “googling” and lots of back and forth all while taking inspiration from people who faced the same situation before us, we finally came up with a method that we felt would work well for us. This post is sort of a recap of the steps we took and what we agreed on.

Before that let’s take a quick overview of what we are going to learn.

  1. Common Terminologies when accessing resources
  2. What is API and RESTful API?
  3. The best way of writing Standard API
  4. Practical nodejs example

Terminologies used

Before we dive into the meats of the topic, let's look at some common terminologies used when trying to get access to resources and that we will make use of in this post.

URL

Stands for uniform resource locator. A path at which a resource is located.

URI

Stands for uniform resource identifier. URI can be a name, locator for an online resource.URL can be a subset of URI.

Resource

Is an object or a representation of something, which HTTP methods can be performed on it. In other words, any concept that might be the target of an author’s hypertext reference must fit within the definition of a resource. e.g. users,comments,posts.

API endpoint

These are touch points of communication for an API, an endpoint includes the URL of a server or service.

Collections

Collection of resources.

HTTP METHODS

These are actions performed to a resource

GET /users fetch the list of all posts

POST /users create a new user

PUT /users/1 this update all payload of a resource

PATCH /users/1 you send only specified parameter for an update in request

DELETE /users/1 this delete the user with an id of 1

Since we have our useful concept in our belt lets move forward

APIs and Restful APIs

API stands for application program interface. Is a messenger between one software and other software. Example, Software A make structured requests. API consumes request, send to Software B for a response. API returns the desired structured response to software A.

One of many types of APIs is web API (web services). Which also have many types, e.g Simple Object Access Protocol (SOAP), Remote Procedure Call (RPC), Representation State Transfer (REST) which we will have a brief glance at it.

REST API

Stands for Representation State Transfer, It is an architecture style for designing loosely coupled applications over HTTP.

Terminologies associated with RESTful API

Representational means there is a different presentation of resources from the server to the client. This different presentation in readable format can be json, XML, image, HTML, and etc.

Client-server client application and server application must be to evolve separately without any dependency on each other. A client should only know resource URIs and that’s all.

Stateless it simply means No client session on the server. It treats each and every HTTP request as new. No session no history, Period.

Hint: Above, I just showed the short explanation of common terminologies in REST, these are not guarding principle for REST. If you want to know those check it here

Since we now know what REST API is. Let’s see best practices of writing standard REST API

1. URL contains a resource(nouns) and resource should be plural

It’s always good practice naming URL collection resource and sub-collections resource as nouns and the nouns are plural

//good practice /users/3 or users/3/posts or /users/3/posts/1/comments

//bad practice //user/3 or user/3/post or user/3/post/1/comment

2. The HTTP methods(verbs) should define the action

If you’re creating a resource use POST method. Which indicate your adding resource.

//good practice HTTP method define the add action to a resource

POST /posts

//bad practice Both HTTP method and resource define the action

POST /addposts

When fetching resources use GET method. Which define your fetch action.

//good practice HTTP method define the fetch action to a resource

GET /posts

//bad practice Both HTTP method and resource define the action

GET /getposts

If your updating resources use PUT/PATCH method. which define your update action on a resource.

//good practice HTTP method define the update action to a resource

PUT /posts/1

//bad practice Both HTTP method and resource define the action

PUT/posts/1/ update

When deleting a resource use DELETE method. Which define your delete action on a resource.

//good practice HTTP method define the delete action to a resource

DELETE /posts/1

//bad practice Both HTTP method and resource define the action

DELETE/posts/1/delete

3. Depict Resources Hierarchy through URIs

Often times resource contains sub-resources, like posts (resource) and comments (sub-resource). The best practice is first, start with a resource itself then its sub-resource. This is what we call Depict

GET /posts/4/comments/5 //get comments of id 5 which belong to post of id 5

I know your saying but Chrisostom, can’t you just simplify things. Like,

//GET comments/5

OK your right that also works, one reason to do it other way is a sub-resource will not exist without a resource for our case comment will not exists without a post, and another reason is it’s just good practice since you’re very explicit to the API consumer

4. Don’t misuse safe methods

Safe methods are HTTP methods that don’t change the state of the resource in the server. E.g. GET, HEAD, OPTIONS and TRACE.

//GET /posts/3/delete //intended to update a resource with GET method

Why? Because a consumer of the API expects the state of the server will be the same no matter how many times they call the APIs endpoint. This guarantee is very important.

Imagine you’re trying to fetch data but you’re deleting it in the background. Its weird isn’t it.

Hint GET should never be used to any change business data.

5. Use HTTP headers for serialization format

Client and server need to know which format is used for communication. Specify the format in the HTTP-headers

Content-type define request format

Accept define lists of response format

6. Versioning your APIs.

Change in an API is inevitable as your knowledge and experience improve. This is actually challenging when you have existing client integration.

When to make these changes in APIs.

Removing any part of API for some reasons.

A change in the format of response data for one or more calls.

Change in response type (i.e. changing an integer to float).

Three ways we can version our API. Using URIs versioning, custom request header, accept header. For this article, I will show you URI versioning.

https://eample.com/api/v1/posts/1 this for aversion one

https://example.com/api/v2/posts/1 this is for version two

7. HATEOAS

stands for Hypermedia as Engine Of Application state is a principle which hyperlinks is used to create better and easy navigation through the API.

8. Right HTTP response code status.

The HTTP status codes show a response of the request, it can be failure or success.

Hint HTTP codes are standards they should not be changed.

Responses and their status codes

2xx

200 Ok

The request has succeeded

201 Created

Indicate successful on new resource creation

3xx Redirecting

301 Moved Permanently

This response code means that the URI of the requested resource has been changed permanently

4XX Client errors

400 Bad Request

This response means that the server could not understand the request due to invalid syntax

401 Unauthorized

Although the HTTP standard specifies “unauthorized”, semantically this response means “unauthenticated”. That is, the client must authenticate itself to get the requested response

5xx server errors

500

The server has encountered a situation it doesn’t know how to handle.

For a list of all HTTP code please check Mozilla Developer Center here

9. Pagination,Searching ,sort,filtering

When an HTTP GET request is issued on a resource route, all the tables rows are returned, this can not be a challenge if your fetch 100 rows data. But what if you have thousands or millions of rows, its a disaster. Clients should consume and display only a fraction of the rows available in the database and then fetch more rows when needed, this is when pagination comes in handy.

Pagination

This is the simplest form of pagination which takes the limit and offset

Limit/Offset Paging would look like GET /posts?limit=5&offset=10. This query would return the 5 rows starting with the 10th row.

Sorting

Clients should be able to specify the column to sort by and the order (ascending or descending). The simplest way to do this is to define a query parameter (I’ll use sort).

GET /posts?sort=-created_at

Returns posts sorted with descending order of created date time.

Searching

This is a powerful way to fetch data since it involves passing multiple parameters to the URI

GET /posts?status=viewed&tag=technology

Returns posts with a status of viewed and contains tag technology

Filtering

Filtering can be implemented as a query parameter named for the field to be filtered on, the value should (naturally) be the value you need to filter for.

GET /users/123/posts?status=viewed

status represents the filter parameter

10. API Documentation

Is technical content containing instructions about how to effectively integrate and use the APIs. Why document? Because easier maintenance and saves support time and cost.

Pat your self in the back, we have learned a lot seriously. But before we end let's focus on one more thing

Practical nodejs example

I have created a nodejs series on practicing these best practices and I want each and every one of you to give it a glance. I will update the link of the article.

In closing

APIs consumers can be front-end developer in your team or any other developers. The thing is, these developers already have headache maintaining their code. Your API should not be a headache to them. I believe this article will lead you to write best and standard Restful APIs.

I would like to acknowledge restufulapi.net website which helped me writing this resource. Please check it here for more practice.

If you like the article please give a clap or share, for any query corresponding the article put them in section comment below, otherwise, you can email me chrissoemma@gmail.com, check my twitter here, LinkedIn here.

Happy to give back to developers community.

#BACKTODEVELOPERSCOMMUNITY(#BDC).

--

--