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:
- Basics of Express JS and Node JS.
- Postman should be installed.
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:
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, () => { }); |
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.
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.
Step 5: Click “Send” to make the request.
Step 6: Getting the response from server.
For `/hello`, the response should be “Hello, Postman!”. You will get this in Response window at bottom.
Step 7: Test Other Endpoints
Repeat the process for `/greet/:name` and `/calculate`. Adjust the URL and request method accordingly.
- Navigate to the “Params” tab to add parameters – For `/greet/:name`, we will set params too. In below image you can see how to set it.
- Navigate to the “Body” tab to add body to request – For `/calculate`, we will send two number in body itself and below image you can see it.