Express.js: Introduction to API


2 min read

API. What is it?

Application Programming Interface (API) in just an interface to interact with data. In context of a full-stack web app, frontend app request the data through the API which is defined in the server side. Generally, the data is exchanged in JSON(JavaScript Object Notation) format.

Let's setup an API in express. Now, when I said setting up an API, it simply refers to handling the user request for specific routes.

const express = require('express');
const app = express();
const data = require("./data.js");

// This is what setting up an API means
app.get("/", (req, res) => {
    // 'json()' sends response in JSON format 

app.listen(5000, () => console.log("Listening in Port 5000!!!"));

You might be familiar with the above code format if you have read my previous article about Express.js Basic Introduction. The extra things are:

  • We import './data.js' which contains JSON data in it. Instead of using a database, we are using JS file for simplicity.

  • When the user sends a request to '/' route using GET method(which happens by default), then the callback function of 'app.get()' executes.

  • Now, instead of 'res.send()', we use 'res.json()' to send JSON data as response.

That our basis API setup in Node.js and you can setup API for multiple routes using multiple http methods(GET, POST, PUT, DELETE). That's all for now!