Open In App

How to test API Endpoints with Postman and Express ?

Postman, a popular API development and testing tool allowing developers to interact with APIs. In this guide, we’ll explore the basics of testing API endpoints using Postman and Express, providing clear steps and examples.

Prerequisites:

Steps to test API endpoints with Postman & Express:

Step 1: Create a basic Express application and install the required dependencies.



npm init -y
npm install express body-parser

Folder Structure:

Folder Structure

The updated dependencies in package.json file will look like:



"dependencies": {
"body-parser": "^1.20.2",
"express": "^4.18.2"
}

Step 2: Create a file named `server.js` and add the following code:




//server.js
 
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
 
app.use(bodyParser.json());
 
// /hello endpoint
app.get("/hello", (req, res) => {
    res.send("Hello, Postman!");
});
 
// /greet/:name endpoint
app.get("/greet/:name", (req, res) => {
    const { name } = req.params;
    res.send(`Hello, ${name}!`);
});
 
// /calculate endpoint
app.post("/calculate", (req, res) => {
    const { num1, num2 } = req.body;
 
    if (num1 === undefined || num2 === undefined) {
        return res
            .status(400)
            .json({
                error: "Both num1 and num2 are required in the request body.",
            });
    }
 
    const result = num1 + num2;
    res.json({ result });
});
 
app.listen(3000, () => {
    console.log("Server is running on http://localhost:3000");
});

Run your server with the following command and access it at `http://localhost:3000`:

node server.js

Step 3: Create a New Request

Open Postman, click “New,” and select ” Add Request.” Give it a name and save it in a collection.

Creating Collection and new request

Step 4: Define Request Details

Enter the request URL. For example, use `http://localhost:3000/hello`. Select the HTTP method (GET) from the dropdown menu.

Setting url and method type

Step 5: Click “Send” to make the request.

Send button

Step 6: Getting the response from server.

For `/hello`, the response should be “Hello, Postman!”. You will get this in Response window at bottom.

Response from server

Step 7: Test Other Endpoints

Repeat the process for `/greet/:name` and `/calculate`. Adjust the URL and request method accordingly.

Sending params in url

Output GIF:

Final Output


Article Tags :