Tuesday, November 23, 2021

How to Mock an API using JSON Placeholder

Public JSONPlaceholder API

JSONPlaceholder is a free, open-source mock REST API service offering realistic example data (including users, posts, comments, todos, and more) for prototyping and testing front-end applications—no sign-up or backend needed. It supports standard HTTP methods, though only GET requests return persistent data.

Retrieve a single user

Retrieve all users

Note: While JSONPlaceholder accepts POST, PUT, PATCH, and DELETE requests, those operations are simulated and the server returns a success response, but no real data changes will persist after a page reload.

Local JSON Server

To get your mock data to persist, run the JSONPlaceholder API locally using json-server:

npm install -g json-server

Create a db.json file:

{
  "users": [
    { "id": 1, "name": "Alice", "email": "alice@example.com" },
    { "id": 2, "name": "Bob", "email": "bob@example.com" }
    { "id": 3, "name": "John", "email": "john@example.com" }
  ]
}

Start the server:

json-server --watch db.json --port 3000

The API is now available at http://localhost:3000/users, with full support for GET, POST, PUT, PATCH, and DELETE—persistent changes are saved in db.json.

Local Examples using json-server

GET all users / get one user:

POST — create a new user:

PUT — replace a user entirely:

PATCH — update part of a user:

DELETE — remove a user:

Summary

JSONPlaceholder is perfect for testing GET user data retrieval. For real mock APIs with persisting data, use json-server locally. It’s a lightweight and efficient way to prototype, test, demo, and learn REST APIs.

No comments:

Post a Comment