Build Your First REST API with Node.js

REST APIs are the backbone of modern web and mobile applications. If you’re learning backend development, building a REST API using Node.js is one of the best places to start.

In this guide, you’ll learn how to build your first REST API in Node.js using Express.js, with simple examples you can run locally.


Prerequisites

Before starting, make sure you have:

  • Basic JavaScript knowledge
  • Node.js installed
  • A code editor (VS Code recommended)

Check Node.js installation:

node -v
npm -v


What Is a REST API?

A REST API allows applications to communicate with each other using HTTP methods:

  • GET – Fetch data
  • POST – Create data
  • PUT – Update data
  • DELETE – Remove data

REST APIs usually return data in JSON format.


Step 1: Create a New Node.js Project

Create a folder and initialize your project:

mkdir my-first-api
cd my-first-api
npm init -y

This creates a package.json file.


Step 2: Install Required Packages

We’ll use Express.js, a popular Node.js framework.

npm install express

Optional (for auto restart):

npm install nodemon --save-dev


Step 3: Create the Server File

Create a file named index.js:

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

app.use(express.json());

const PORT = 3000;

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Run the server:

node index.js

Visit 👉 http://localhost:3000


Step 4: Create Your First API Route

Add a GET API:

app.get('/', (req, res) => {
  res.json({ message: 'Welcome to my first REST API!' });
});

Now open the browser:

http://localhost:3000/

You’ll see JSON output


Step 5: Create a GET API (Fetch Data)

Let’s return a list of users:

app.get('/users', (req, res) => {
  const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Sara' }
  ];
  res.json(users);
});

URL:

GET /users


Step 6: Create a POST API (Add Data)

app.post('/users', (req, res) => {
  const user = req.body;
  res.status(201).json({
    message: 'User created',
    user
  });
});

Test using Postman or Thunder Client:

POST /users
{
  "name": "Alex"
}


Step 7: Create PUT API (Update Data)

app.put('/users/:id', (req, res) => {
  res.json({
    message: `User ${req.params.id} updated`
  });
});


Step 8: Create DELETE API

app.delete('/users/:id', (req, res) => {
  res.json({
    message: `User ${req.params.id} deleted`
  });
});


Step 9: Test Your API

You can test APIs using:

  • Postman
  • Thunder Client (VS Code extension)
  • curl command

Suggested Project Structure (Beginner)

my-first-api
│
|--- index.js
|--- package.json
|--- node_modules

As your app grows, you can separate routes, controllers, and services.

Best Practices for Node.js REST APIs

  • Use environment variables
  • Validate input
  • Use async/await
  • Add logging

Frequently Asked Questions

Is Node.js good for REST APIs?

Yes, Node.js is widely used…

Which framework is best for Node.js REST API?

Express.js is the most popular…

Can beginners learn REST API in Node.js?

Absolutely…

Send Email with Attachment File from Lambda (Nodejs)

You can create a lambda (nodejs) with the following code (written in typescript) to send an email to a user with a file attachment.

In the below example, we are first getting the content from S3 bucket, then creating a csv and sending it to a user (SES verified user).

import {
    S3Client,
    GetObjectCommand
  } from "@aws-sdk/client-s3";
  import { SESClient, SendRawEmailCommand } from "@aws-sdk/client-ses";
  import { Readable } from "stream";
  const s3Client = new S3Client({ region: "ap-southeast-2" });
  const sesClient = new SESClient({ region: "ap-southeast-2" });


  export const sendEmail = async () => {
    const senderEmail = process.env.SENDER_EMAIL_ADDRESS;
    const recipientEmail: any = process.env.RECIEVER_EMAIL_ADRESS;
    const subject = "SUBJECT here";
    const bodyText =
      "Hello,\r\n\nPlease see the attached csv file \n\nThanks";
  
    const getObjectCommand = new GetObjectCommand({
      Bucket: process.env.BUCKET,
      Key: process.env.BUCKET_KEY,
    });
  
    const attachmentData = await s3Client.send(getObjectCommand);
    const attachmentBuffer = await streamToBuffer(
      attachmentData.Body as Readable
    );
  
    const attachmentBase64 = attachmentBuffer.toString("base64");
  
    const emailData =
      `From: ${senderEmail}\r\n` +
      `To: ${recipientEmail}\r\n` +
      `Subject: ${subject}\r\n` +
      `MIME-Version: 1.0\r\n` +
      `Content-Type: multipart/mixed; boundary="boundary"\r\n\r\n` +
      `--boundary\r\n` +
      `Content-Type: text/plain; charset=utf-8\r\n` +
      `${bodyText}\r\n\r\n` +
      `--boundary\r\n` +
      `Content-Type: application/octet-stream\r\n` +
      `Content-Disposition: attachment; filename="file.csv"\r\n` +
      `Content-Transfer-Encoding: base64\r\n\r\n` +
      `${attachmentBase64}\r\n\r\n` +
      `--boundary--`;
  
    const sendRawEmailCommand = new SendRawEmailCommand({
      RawMessage: {
        Data: Buffer.from(emailData),
      },
      Source: senderEmail,
      Destinations: [recipientEmail],
    });
  
    const result = await sesClient.send(sendRawEmailCommand);
    return result.MessageId;
  }

  async function streamToBuffer(stream: Readable): Promise<Buffer> {
    return new Promise((resolve, reject) => {
      const chunks: Uint8Array[] = [];
      stream.on("data", (chunk) => chunks.push(chunk));
      stream.on("end", () => resolve(Buffer.concat(chunks)));
      stream.on("error", reject);
    });
  }

How to connect to SQL database from Lambda using Nodejs

To connect to SQL database from lambda, I am using Nuget package ‘mssql’.

For this, I have created a serverless application using Nodejs 16.x.

To connect to SQL database from lambda, I am using Nuget package ‘mssql’.

In your serverless application, install mssql like below –

npm install mssql

Usage

I am using Typescript and DBConfig used above is just an interface.
Also replace all the config with your database credentials.

import sql from "mssql";

const config : DBConfig = {
 user: ${process.env.DB_USER},
 password: ${process.env.DB_PASSWORD},
 server: ${process.env.DB_SERVER},
 database: ${process.env.DATABASE},
 options: {
  trustServerCertificate: true,
 },
};

export const run = async () => {
 try {
  await sql.connect(config);
  const result = await sql.query`Select * from [TableName]`;
  var result = result.recordset;
}
catch (err) {
 console.error("Error:", err);
 return {
  statusCode: 500,
  body: JSON.stringify({
  message: "Error accessing the database.",
  error: err,
  }),
 };
}
}

Please note that the RDS and lambda should be in same VPC settings. If while running lambda, you get a timeout error, do verify the VPC settings for both RDS and lambda. If they are in different VPC, then you have to do further settings. Please refer to AWS documentation for that.

Also make sure the IAM role in lambda should have permission to access RDS

Refer to this if you are looking to send an email with attachment from lambda.

Generate a hex encoded HMAC-SHA256 hash using Crypto in Nodejs

How to generate an encoded hash in nodejs using crypto

import { Service } from './service';
import crypto from 'crypto';

export class TestService extends Service {
    private _secretKey: string;

    constructor() {
        this._secretKey = '1234567890';
		this._userId = '123';
    }

    /**
     * Get Hex encoded hash of secret key
     */
    private GetHashKey(): string {
        return crypto
            .createHmac('sha256', this._secretKey)
            .update(this._getUserString(this._userId))
            .digest('hex');
    }
}

Interested in Cryptocurrency. Register and start investing here

Earn a side income by affiliate marketing. Learn here how to do it.