Create an API with json-server

Reference: https://medium.com/@belgacem.benltaif/create-an-api-with-json-server-af5b5687c83d

 

Create an API with json-server

Hello, in this article we will create together an API rest based on node js in 4 steps, without needing a database (yes without database !!!).

Step 1: Install json-server:

You can install JSON-server globally or in your project:

npm install -g json-server

Step 2 Create a directory for the project:

mkdir gasston-api & cd gasston-api

Step 3 Creating the data:

Create your data structure in a /db.json file:

{

"users": [

{

"id": 1,

"first_name": "John",

"last_name": "Smith",

"phone": "00005"

},

{

"id": 2,

"first_name": "James",

"last_name": "Bond",

"phone": "0007"

}

],

"posts": [

{

"title": "hello title",

"body":"hello c'est le body",

"id": 1

},

{

"id": 2,

"title": "hello title 2",

"body":"hello c'est le body 2",

}

]

}

Step 4 Launch your server:

node json-server db.json

The server is launched you can test your API:

http://localhost:3000/

http://localhost:3000/clients/

http://localhost:3000/arcticles/

http://localhost:3000/arcticles/1
...
 

You can send POST / GET / PUT / DELETE queries (you need to add “Content-Type: application / json in the header of your queries)

PS: you can start the server in watch mode

node json-server --watch db.json