Crafting a Dynamic User API with Express.js: Empowering Your Applications with Random User Data
Mahabubur Rahman
Posted on February 29, 2024
Let's create an Express API that serves random user data. When you hit the URL, it will provide one random user data every time.
An API, or Application Programming Interface, serves as a connection between frontend and backend systems through URLs. It enables data communication between two or more computers or programs. so let's start to make it!
To initialize our Node project, first, create a folder named "random-user". Then, we use Node Package Manager (NPM) to set up the project:
mkdir random-user
cd random-user
or create manually.
npm init
It's take some information from you.
- or use -y a flag to accept default values:
npm init -y
Install Express server:
npm install express
Install CORS to allow access from anywhere:
npm install cors
Optionally, install Nodemon to automatically restart the server:
npm install nodemon
or install it globally:
npm install -g nodemon
Now that our project initialization is complete, the folder structure will look like this:
random-user/
|__ node_modules/
|__ package-lock.json
|__ package.json
|__ server.js
|__ .gitignore
To achieve this structure, you can follow these steps:
- Create the server.js file and add your code.
- Create a .gitignore file to ignore the node_modules directory.
To customize the package.json file with the provided scripts and configuration, you can follow these steps:
- Open the package.json file in your text editor.
- Modify the scripts section to include the start script:
"scripts": {
"start": "nodemon server.js",
},
or
"scripts": {
"start": "node server.js",
},
Change the main key to point to server.js:
"main": "server.js"
Add a type key with the value "module":
"type": "module",
Your package.json file should now look like this:
{
"name": "express-random-user",
"version": "1.0.0",
"description": "",
"main": "server.js",
"type": "module",
"scripts": {
"start": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"nodemon": "^3.0.3"
}
}
now start our server using
npm run start
Certainly! To create a folder named "data" and place a JSON file named "user.json" inside it, you can follow these steps
mkdir data
- or create manually Inside the "data" folder, create a file named "user.json".
You can manually create and edit this file using a text editor, or you can use an online JSON generator tool like the ones you mentioned (e.g., json-generator.com or jsongenerator.io) to generate JSON data. Here's an example of JSON data:
{
"name": "Alice Smith",
"email": "alice.smith@example.com",
"address": {
"street": "123 Main Street",
"city": "New York",
"state": "NY",
"country": "USA",
"zipcode": "10001"
}
}
Repeat this process to generate at least 10 JSON objects and add them to the "user.json" file.
now working on our server.js. their use is first import our express and cors.
import express from "express";
import cors from "cors";
Create an express instance
const app = express();
Enable CORS with credentials and allow the origin
app.use(cors({ credentials: true, origin: ["http://localhost:3000"] }));
Initialize port from an environment variable or default to 5050
const PORT = process.env.PORT || 5050;
listen or create to the server on port 5050
app.listen(PORT, () => console.log(`Server Running on Port ${PORT}`));
after running our server on see in the terminal
Server Running on Port 5050
With these changes, your Express server should be properly configured to use Express and Cors, initialize the port from environment variables, and start listening on the specified port. When you run your server, you should see the message "Server Running on Port 5050" in the terminal if everything is set up correctly.
Import the JSON file named "user.json" as users with the assertion { type: "json" }.
import users from "./data/user.json" assert { type: "json" };
Create a function called generateRandom to generate random user data every time it's called.
const generateRandom = () => {
// body
}
Extract the names, emails, and addresses from the user's data by mapping over each user object.
const name = users.map((user) => user.name);
use a map for looping the users and filtering by keys. as the same for email and address.
const email = users.map((user) => user.email);
const address = users.map((user) => user.address);
now get the random value by Math. random function. in their name is an array that we create by map. so in name, you are trying to get their index by random. so first we use random function multiplay by name size. In there, we get a floating value that why that method wrapping in the floor method.
Retrieve the random name, email, and address using the generated random indices.
const randomName = name[Math.floor(Math.random() * name.length)];
as same we do in email and address.
const randomEmail = email[Math.floor(Math.random() * email.length)];
const randomAddress = address[Math.floor(Math.random() * address.length)];
Return the random name, email, and address from the function
return {
randomName,
randomEmail,
randomAddress,
};
after we see our random data generator functionality.
const generateRandom = () => {
const name = users.map((user) => user.name);
const email = users.map((user) => user.email);
const address = users.map((user) => user.address);
const randomName = name[Math.floor(Math.random() * name.length)];
const randomEmail = email[Math.floor(Math.random() * email.length)];
const randomAddress = address[Math.floor(Math.random() * address.length)];
return {
randomName,
randomEmail,
randomAddress,
};
};
Create a GET method to retrieve random data:
app.get("/api/random", (req, res, next) => {
// body
}
This GET method listens on the "/api/random" URL and takes a callback function with parameters req (request), res (response), and next (middleware to pass to the next function).
The req object represents the request to retrieve all objects from Express, while the res object is used to respond with data. The next object is middleware to pass control to the next function in the stack.
in our get method, we get generate a random function into random data
const randomData = generateRandom();
after we use try catch for more secure our API call
try {
// body
} catch (error) {
// body
}
in try we send a response to our random data, and in catch, we console the error if we get it.
app.get("/api/random", (req, res, next) => {
const randomData = generateRandom();
try {
res.status(200).send(randomData);
} catch (error) {
console.error(error);
}
});
it's our full get method to get it. our random data is ready to hit.
now our full API URL is
http://localhost:5050/api/random
if you hit this URL in the browser you get data by random by refresh. but make sure your server is running correctly.
the full code server.js
import express from "express";
import cors from "cors";
import users from "./data/user.json" assert { type: "json" };
const app = express();
const PORT = process.env.PORT || 5050;
app.use(cors({ credentials: true, origin: ["http://localhost:3000"] }));
const generateRandom = () => {
const name = users.map((user) => user.name);
const email = users.map((user) => user.email);
const address = users.map((user) => user.address);
const randomName = name[Math.floor(Math.random() * name.length)];
const randomEmail = email[Math.floor(Math.random() * email.length)];
const randomAddress = address[Math.floor(Math.random() * address.length)];
return {
randomName,
randomEmail,
randomAddress,
};
};
app.get("/api/random", (req, res, next) => {
const randomData = generateRandom();
try {
res.status(200).send(randomData);
} catch (error) {
console.error(error);
}
});
app.listen(PORT, () => console.log(`Server Running on Port ${PORT}`));
congratulations. you make it 😃.
GitHub repository: https://github.com/mahabubr/express-random-user
Posted on February 29, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.