Comprehensive Guide to json-server for Efficient API Development

Comprehensive Guide to json-server for Efficient API Development

Json-server is a module that provides you with a simple way to set up a RESTful JSON-based API. It is highly effective for prototyping and mocking, allowing developers to focus more on the application instead of spending too much time on back-end intricacies.

Getting Started

To get started with json-server, first, you need to install it using npm:

npm install -g json-server

Create a db.json file that will act as your database and write the following structure:

 {
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
} 

Running the Server

Once your db.json is set up, you can start the server with:

json-server --watch db.json

By default, json-server will be available on http://localhost:3000.

API Endpoints

json-server automatically creates an API from the db.json you provided. Here are some example endpoints:

Fetch All Posts

GET /posts

Example Response:

 [
  { "id": 1, "title": "json-server", "author": "typicode" }
] 

Fetch a Single Post

GET /posts/1

Example Response:

 { "id": 1, "title": "json-server", "author": "typicode" } 

Create a New Post

POST /posts

Request Body:

 { "title": "new post", "author": "author name" } 

Example Response:

 { "id": 2, "title": "new post", "author": "author name" } 

Update a Post

PUT /posts/1

Request Body:

 { "title": "updated title", "author": "updated author" } 

Example Response:

 { "id": 1, "title": "updated title", "author": "updated author" } 

Delete a Post

DELETE /posts/1

Complete Application Example

Let’s build a simple application where we can view, create, update, and delete posts using json-server.

HTML Code

   
  Simple Blog
 
  

Simple Blog

With the above setup, you have a simple blog application fetching data from json-server.

Hash: 6f3ee38d88aa6dde9967b8b7a821c8be6caa027a327298ba6684921c3f8b78c2

Leave a Reply

Your email address will not be published. Required fields are marked *