Working with json-server is a great way to simulate a backend server and practice API interactions like GET, POST, PUT, PATCH, and DELETE.
What is json-server?
1. Prerequisite: Node.js
node -v npm -v
2. Install json-server
npm install -g json-server@0.17.4
1. Start the Server
Create a db.json file in your working directory with some initial data. Example:
{ "posts": [ { "id": 1, "title": "First Post", "content": "Hello World!" }, { "id": 2, "title": "Second Post", "content": "Learning JSON-Server" } ] }
json-server --watch db.json
2. Explore Endpoints
The server automatically creates RESTful endpoints for each collection in db.json:
Postman is a tool for making HTTP requests to test APIs. Here’s how to perform each operation with Postman:
1. GET (Fetch Data)
2. POST (Add New Data)
{ "id": 3, "title": "New Post", "content": "This is a new post" }
3. PUT (Replace Entire Resource)
Body (JSON):
{
"title": "Updated Title"
}
Result: Replaces the entire resource with the provided data.
Before:
{ "id": 2, "title": "Second Post", "content": "Learning JSON-Server" }
After:
{ "title": "Updated Title" }
4. PATCH (Update Specific Fields)
node -v npm -v
Result: Updates only the specified field in the resource.
Before:
npm install -g json-server@0.17.4
After:
{ "posts": [ { "id": 1, "title": "First Post", "content": "Hello World!" }, { "id": 2, "title": "Second Post", "content": "Learning JSON-Server" } ] }
5. DELETE (Remove Data)
Key Differences Between PUT and PATCH
PUT
PATCH
What I Learned:
Day 19 Crushed.
The above is the detailed content of My React Journey: Day 19. For more information, please follow other related articles on the PHP Chinese website!