JSON Server Setup - Fake REST API for Angular
JSON Server Introduction
JSON Server is used when we want to use all API operations like GET, POST, PUT, and DELETE with Angular.
Free APIs mostly allow only GET operations.
Editing, deleting, or updating data is not allowed on free public APIs.
To practice full CRUD operations, JSON Server is required.
Installing JSON Server
JSON Server is installed using npm.
The same command works on Windows, Linux, or Ubuntu.
If permission issue comes, sudo can be used.
Command:
Project Folder Setup
A new folder is created for APIs.
Inside the folder, a JSON file is created.
The file name is usually db.json.
db.json File
This file contains the API data.
Data is written in JSON format.
Initially, sample data is copied from documentation for testing.
Example:
Running JSON Server
JSON Server is run using npx command.
The command must be run in the same folder where db.json exists.
Command:
JSON Server runs on port 3000.
Multiple APIs are created automatically based on objects in db.json.
Testing API in Browser
The root URL shows all available APIs.
Each object becomes an endpoint.
Posts, comments, and profile APIs are visible and accessible.
Thunder Client Introduction
Thunder Client is a tool to test APIs.
It is a VS Code extension.
It is lightweight and easy to use.
It is an alternative to Postman.
Installing Thunder Client
Thunder Client is installed from VS Code extensions.
After installation, its icon appears in the sidebar.
Testing GET API
GET method is used to fetch data.
API URL is pasted in Thunder Client.
On sending request, status 200 means success.
Response data is shown correctly.
Creating Custom API (Users)
A new object is created inside db.json.
Object name becomes the API endpoint.
An array is used to store multiple users.
Example:
Adding More Users
More user objects are added inside the users array.
Same keys are used for all users.
JSON format must remain correct.
Testing Users API
After restarting JSON Server, only users API is available.
The users endpoint is tested in Thunder Client.
Data is returned successfully with status 200.