API Example with Dynamic Routes
Create a JSON File with User Data
We’ll start by storing our user data in a separate JSON file. Create a folder called data
and inside it, create a file named:
user.json
[
{
"id": 1,
"name": "Anil",
"age": 30,
"email": "anil@test.com"
},
{
"id": 2,
"name": "Sam",
"age": 32,
"email": "sam@test.com"
},
{
"id": 3,
"name": "Peter",
"age": 20,
"email": "peter@test.com"
},
{
"id": 4,
"name": "Bruce",
"age": 18,
"email": "bruce@test.com"
}
]
Set Up Express Server
Now, create an Express server in your index.js
or app.js
file:
import express from "express";
import userData from "./data/user.json" assert { type: "json" };
const app = express();
const PORT = 3200;
// Default route to send full user list
app.get("/", (req, resp) => {
resp.send(userData);
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Fetch a Single User by ID (Dynamic Route)
Create a dynamic route to fetch user data using the ID passed in the URL:
app.get("/user/:id", (req, resp) => {
const id = req.params.id;
const filteredData = userData.filter((user) => user.id == id);
resp.send(filteredData);
});
Explanation:
:id
is a dynamic parameter.req.params.id
captures the ID from the URL.- We use
filter()
to match the ID in the JSON data.
GET /user/2
→ returns data of Sam.
Fetch a User by Name (Case-Insensitive Match)
You can also get users by their name:
app.get("/user-by-name/:name", (req, resp) => {
const name = req.params.name;
const filteredData = userData.filter(
(user) => user.name.toLowerCase() === name.toLowerCase()
);
resp.send(filteredData);
});
Example:
GET /user-by-name/peter
→ returns Peter’s details.