Crafting a Dynamic User API with Express.js: Empowering Your Applications with Random User Data

mahabubr

Mahabubur Rahman

Posted on February 29, 2024

Crafting a Dynamic User API with Express.js: Empowering Your Applications with Random User Data

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
Enter fullscreen mode Exit fullscreen mode

or create manually.

npm init
Enter fullscreen mode Exit fullscreen mode

It's take some information from you.

  • or use -y a flag to accept default values:
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install Express server:

npm install express
Enter fullscreen mode Exit fullscreen mode

Install CORS to allow access from anywhere:

npm install cors
Enter fullscreen mode Exit fullscreen mode

Optionally, install Nodemon to automatically restart the server:

npm install nodemon 
Enter fullscreen mode Exit fullscreen mode

or install it globally:

npm install -g nodemon
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

To achieve this structure, you can follow these steps:

  1. Create the server.js file and add your code.
  2. 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:

  1. Open the package.json file in your text editor.
  2. Modify the scripts section to include the start script:
"scripts": {
    "start": "nodemon server.js",
},
Enter fullscreen mode Exit fullscreen mode

or

"scripts": {
    "start": "node server.js",
},
Enter fullscreen mode Exit fullscreen mode

Change the main key to point to server.js:

"main": "server.js"
Enter fullscreen mode Exit fullscreen mode

Add a type key with the value "module":

"type": "module",
Enter fullscreen mode Exit fullscreen mode

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"
  }
}
Enter fullscreen mode Exit fullscreen mode

now start our server using

npm run start
Enter fullscreen mode Exit fullscreen mode

Certainly! To create a folder named "data" and place a JSON file named "user.json" inside it, you can follow these steps

mkdir data
Enter fullscreen mode Exit fullscreen mode
  • 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"
    }
}
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

Create an express instance

const app = express();
Enter fullscreen mode Exit fullscreen mode

Enable CORS with credentials and allow the origin

app.use(cors({ credentials: true, origin: ["http://localhost:3000"] }));
Enter fullscreen mode Exit fullscreen mode

Initialize port from an environment variable or default to 5050

const PORT = process.env.PORT || 5050;
Enter fullscreen mode Exit fullscreen mode

listen or create to the server on port 5050

app.listen(PORT, () => console.log(`Server Running on Port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode

after running our server on see in the terminal

Server Running on Port 5050
Enter fullscreen mode Exit fullscreen mode

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" };
Enter fullscreen mode Exit fullscreen mode

Create a function called generateRandom to generate random user data every time it's called.

const generateRandom = () => {
   // body
}
Enter fullscreen mode Exit fullscreen mode

Extract the names, emails, and addresses from the user's data by mapping over each user object.

const name = users.map((user) => user.name);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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)];
Enter fullscreen mode Exit fullscreen mode

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)];
Enter fullscreen mode Exit fullscreen mode

Return the random name, email, and address from the function

return {
    randomName,
    randomEmail,
    randomAddress,
};
Enter fullscreen mode Exit fullscreen mode

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,
  };
};
Enter fullscreen mode Exit fullscreen mode

Create a GET method to retrieve random data:

app.get("/api/random", (req, res, next) => {
    // body
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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);
  }
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}`));
Enter fullscreen mode Exit fullscreen mode

congratulations. you make it 😃.

GitHub repository: https://github.com/mahabubr/express-random-user

💖 💪 🙅 🚩
mahabubr
Mahabubur Rahman

Posted on February 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related