Building Prototype REST API with JSON for Frontend Newbies and Experts

June, 15 2020 Javascript

Considering that I am more inclined to backend development, a good number of frontend enthusiasts and newbies have reached out to me to open any of my existing REST API to them for consumption, for practice purpose perhaps.

This article explains how you can create a test REST API with JSON, make it fully ready for consumption and consume with an API testing tool (Postman Client).

Go to the link https://nodejs.org/en/download/, download and nodejs.

Install JSON Server by running the command:

npm install -g json-server

Create a file that will be your supposed database of data, we will call the file db.json and add your data. See example below:

{
  "users": [
       { "id"1"name""Nuhu Ibrahim" }
  ],
  "posts": [
       { "id"1"user_id""1""content""Hello World" }
  ]
}

Start the json-server by executing:

json-server --watch db.json

Below are the available resources on the server based on the db.json file:

Resources
  http://localhost:3000/users
  http://localhost:3000/posts

Home
  http://localhost:3000

And below are the routes that are open based on the db.json file (database) content:

GET    /users
GET    /users/1
POST   /users
PUT    /users/1
PATCH  /users/1
DELETE /users/1

GET    /posts
GET    /posts/1
POST   /posts
PUT    /posts/1
PATCH  /posts/1
DELETE /posts/1

Go to https://www.postman.com/downloads/ to download an API test client, the most recommended one called Postman and follow their tutorial on how to use it to consume REST APIs.

Enjoy building your frontend projects without wasting time building a proper backend or waiting for a backend engineer to assist ✌.

Note

Changes will be automatically and safely saved to db.json using lowdb whenever you make POST, PUT, PATCH or DELETE requests.

Your request body JSON should always be object enclosed.

A POST, PUT or PATCH request should includeContent-Type: application/json header to use the JSON in the request body.

You can perform filtering, sorting, full-text search, relationship fetchs; you can also access the json-server remotely, add custom routes, middlewares, authentication and do even a lot more.

Read more about json-server here.

Thoughts

I'd love to hear your thoughts. Let me know in the comments section on twitter or on LinkedIn







By Nuhu Ibrahim

Full Stack Web and Desktop Developer