Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Node.js

To construct our API using JavaScript, we will utilize Express.js, a framework that operates within the Node.js environment. Express.js is designed to streamline the development of APIs by providing a simplified interface atop Node.js.

Setup Environment

Install Node.js:

Download and install Node.js from here.

Create a project directory:

Now, create a project folder and navigate inside that folder using the following command.

 cd C:\Users\yourname\project

Initialize a Node.js project:

To start building a Node.js project, you must first install the project dependencies, which will be achieved through the following command. Type this command in the VSCode terminal inside your project folder. After you run this command, you will notice a package.json file in your project folder.

npm init -y

Install Express, Mongoose, and Dotenv:

Now install the framework and database for this project. express is a web framework, mongoose is a MongoDB object modeling tool, dotenv is used for managing environment variables, and pg is a PostgreSQL client for Node.js.

npm install express mongoose dotenv pg

Create CRUD Endpoints

Creating CRUD (Create, Read, Update, Delete) endpoints in a Node.js application using Express involves defining routes that handle HTTP requests for managing resources. In this example, we'll focus on a resource called items and we have assumed that a database connection has already been established with PostgreSQL database. The code defined below uses some methods from our database.

Define your database schema:

Schemas are tables that have relationships with each other. When creating databases, we need schemas to handle data efficiently. The following code will create your schema. Add the code in a new file called items.js in the same project directory you created.


// models/item.js
const getItems = async (pool) => {
    try {
        const result = await pool.query('SELECT * FROM items');
        return result.rows;
    } catch (error) {
        console.error(error);
        throw error;
    }
};

const createItem = async (pool, name) => {
    try {
        const result = await pool.query('INSERT INTO items (name) VALUES ($1) RETURNING *', [name]);
        return result.rows[0];
    } catch (error) {
        console.error(error);
        throw error;
    }
};

module.exports = { getItems, createItem };


This JavaScript code defines two functions, getItems and createItem, for interacting with a PostgreSQL database in a Node.js application:

  • getItems Function: Retrieves all entries from the items table in the database. It accepts a PostgreSQL connection pool as a parameter, executes a SELECT query, and returns the query results.

  • createItem Function: Adds a new entry to the items table. It takes a connection pool and the item name as parameters, performs an INSERT query using the provided name, and returns the newly created item.

Create your endpoints in Express

You must now define your routes and functions for CRUD operations. This will ensure you have GET and POST methods for your APIs. Add this code to a new file called methods.js in your project directory.

const express = require('express');
const router = express.Router();
const { getItems, createItem } = require('../models/item');

// Get all items
router.get('/items', async (req, res) => {
    try {
        console.log('req.pool', req.pool);
        const items = await getItems(req.pool);
        res.json({ items });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

// Create a new item
router.post('/items', async (req, res) => {
    try {
        // Add input validation as needed
        const newItem = await createItem(req.pool, req.body.name);
        res.json({ item: newItem, message: 'Item created successfully' });
    } catch (error) {
        res.status(500).json({ error: error.message });
    }
});

module.exports = router;


This is how your code will look inside the file.

Run Express.js:

Now that you have created your app, it is time to run it and get your REST API.

node app.js

After running the above command, you will get your REST API. Great work. You now know how to create REST APIs with both Python and Node.js! You can now test your API using Postman and use the same steps mentioned in the Python section above.