How to run internal and external APIs with Express.js

Explain an example of API integration in Express.js.

overview

Express.js is a lightweight web application framework for Node.js, often used to work with APIs. In order to link with the API, it is necessary to send requests and process responses.

Here, we will explain how to link with API in Express.js using the following versions.

Express.js v4.17.1
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

of course. As an example of running the API from the front end, I will add how to use the Fetch API using JavaScript.


How to run the API from the frontend

Using an API on the front end is a common scenario and can be easily implemented using the JavaScript Fetch API. The Fetch API is a browser-provided native API that allows you to make asynchronous HTTP (Ajax) requests.

The example below creates a new user by sending a POST request to the /users endpoint created in Express.js.

index.html

<!DOCTYPE html>
<html>
<body>
  <!-- add button -->
  <button onclick="createUser()">Create User</button>

  <script>
    async function createUser() {
      const response = await fetch('http://localhost:3000/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name: 'John', age: 25 })
      });

      if (!response.ok) {
        const message = await response.text();
        throw new Error(`An error has occurred: ${message}`);
      }

      const user = await response.json();

      console.log(user);
    }
  </script>
</body>
</html>

Commentary

This source code will generate an HTML page for creating a user.

  • Define HTML document and add button:
<!DOCTYPE html>
<html>
<body>
    <!-- add button -->
    <button onclick="createUser()">Create User</button>

This part defines the basic structure of the HTML document and adds a button to create a user. The createUser function will be executed when the button is clicked.

  • Define createUser function:
<script>
async function createUser() {
    const response = await fetch('http://localhost:3000/users', {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({ name: 'John', age: 25 })
    });

This part defines the asynchronous function createUser. This function uses the fetch API to send a POST request to the specified URL (http://localhost:3000/users in this case). In the request body, specify the information of the user to be created in JSON format.

  • Error handling:
    if (!response.ok) {
        const message = await response.text();
        throw new Error(`An error has occurred: ${message}`);
    }

The response.ok property determines whether the response was successful (HTTP status code in the range 200-299). If not successful, generate an error message and throw an error.

  • Response processing and logging:
const user = await response.json();

Parse the response body as JSON using the response.json() method.

server.js

// import the module
const express = require("express");
const app = express();
const path = require("path");

// Specify the directory that hosts the HTML files.
app.use(express.static(path.join(__dirname, "views")));
app.use(express.json());

// Temporary datastore for storing users
let users = [];

app. get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "views", "index.html"));
});

app.get("/users", (req, res) => {
  // return user data as response
  res.json(users);
});

app.post("/users", (req, res) => {
  // get user data from request body
  const user = req.body;
  // add user to datastore
  users. push(user);
  // return the newly created user as a response
  res.json(user);
});

app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Commentary

This code builds a basic Express server that supports listing and creating users. Below is a detailed description of each part.

  • import module
const express = require("express");
const app = express();
const path = require("path");

This part imports two modules, express and path.

  • specify the directory that hosts the HTML files
app.use(express.static(path.join(__dirname, "views")));
app.use(express.json());

Here we use the express.static middleware to host static files in a directory called “views”. It also uses the express.json middleware to allow parsing JSON-formatted request bodies.

  • Temporary data store for storing user data
let users = [];

In this part we define an array to store the created users.

  • routing
app. get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "views", "index.html"));
});

Use the app.get() method to handle GET requests to the root URL ("/"). When a request comes in, it will return the “index.html” file as a response.

  • Get user data
app.get("/users", (req, res) => {
  res.json(users);
});

Returns a list of all saved users in JSON format when a GET request to /users is received.

  • Create User
app.post("/users", (req, res) => {
  const user = req.body;
  users. push(user);
  res.json(user);
});

When a POST request to /users comes in, get the user data from the request body and add it to the data store. Returns the newly created user in JSON format as a response.

  • Start server
app.listen(3000, () => {
  console.log("Server is running on port 3000");
});

Finally, start the server and listen on port 3000. When the server starts, you should see the message “Server is running on port 3000” on the console.

The final directory structure will look like this:

integration
├── node_modules
│ └── (dependency package)
├── views
│ └── index.html
├── server.js
├── package.json
└── package-lock.json

Once done, run the following command to start the server.

node server.js

Once it’s done, access http://localhost:3000 in your browser. Click the button to create the user. A user has been created. Accessing http://localhost:3000/users will display a list of created users.

Send a request to an external API

HTTP client libraries are typically used to send requests to external APIs. Here we use one of them, axios. First, install axios using npm.

npm install axios

external.js

const express = require('express');
const axios = require('axios');

const app = express();

app.get('/data', async (req, res) => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    res.send(response.data);
  } catch (error) {
    res.status(500).send({ message: 'Error occurred' });
  }
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Commentary

This code creates an Express server that gets data from the JSON placeholder API and sends the data as a response.

  • Module import:
const express = require('express');
const axios = require('axios');

This part imports two modules, express and axios. express is the web server framework and axios is the HTTP client library.

  • Create an Express application:
const app = express();

Create an Express application here.

  • Route definition:
app.get('/data', async (req, res) => {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    res.send(response.data);
  } catch (error) {
    res.status(500).send({ message: 'Error occurred' });
  }
});

Defines a handler for GET requests to the /data endpoint. Use axios.get inside an asynchronous function to get data from an external API and send that data as a response. If an error occurs, send a response with status code 500 and an error message.

  • Start Server:
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Finally, start the server and listen on port 3000. When the server starts, you should see the message “Server is running on port 3000” on the console.

test

curl http://localhost:3000/data

summary