Master API Testing with Node.js and Express: Your Ultimate Guide to Building and Testing APIs

Master API Testing with Node.js and Express: Your Ultimate Guide to Building and Testing APIs

Why Test APIs?

API testing is crucial because it ensures that your API works as expected and handles different kinds of requests correctly. This is important for several reasons:

  1. Functionality: Verify that each API endpoint works as intended.
  2. Reliability: Ensure the API can handle valid and invalid requests appropriately.
  3. Performance: Test how the API performs under different conditions, such as high traffic.
  4. Security: Check that the API is secure against common vulnerabilities.


Tools for Testing APIs

There are various tools you can use to test APIs, ranging from command-line utilities to sophisticated GUI applications. Here are a few commonly used ones:

  1. Curl: A command-line tool to send HTTP requests.
  2. Postman: A popular GUI application for testing APIs.
  3. Insomnia: Another GUI tool for API testing, similar to Postman.

Let's Proceed with building our API server first

Step 1: Initialize and Install Express

Before we start with the code, we initialize a Node.js project and install Express.

Initialize a Node.js project:

npm init -y        

This command creates a?package.json?file with default settings for your project.

Install Express:

npm install express        

This command installs Express, a web application framework for Node.js.

Create a new file index.js comprising the below code

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

// Middleware to parse JSON bodies
app.use(express.json());

// GET endpoint
app.get('/kundan', (req, res) => {
    res.status(200).send({
        kundan: '??',
        size: 'large'
    });
});

// POST endpoint with parameter
app.post('/kundan/:id', (req, res) => {
    const { id } = req.params;
    const { logo } = req.body;

    // Check if logo exists in request body
    if (!logo) {
        return res.status(418).send({ message: 'We need a logo!' });
    }

    // Send response with interpolated string
    res.send({
        kundan: `?? with your ${logo} and ID of ${id}`,
    });
});

// Start the server
app.listen(PORT, () => {
    console.log(`Server is running on https://localhost:${PORT}`);
});
        

Let's Break this code as chunks and explain with complete detailing and analysis

Step 2: Creating the Server

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

  • const express = require('express');: This line imports the Express module, which is necessary for creating an Express application.
  • const app = express();: This line creates an instance of an Express application. The?app?variable now holds the Express application.
  • const PORT = 8080;: This line sets the port number to 8080, which is the port on which the server will listen for requests.

Middleware to Parse JSON

app.use(express.json());        

  • app.use(express.json());: This line adds middleware to the Express application that parses incoming JSON request bodies. This is necessary for handling POST requests with JSON data.

GET Endpoint

app.get('/kundan', (req, res) => {
    res.status(200).send({
        kundan: '??',
        size: 'large'
    });
});        

  • app.get('/kundan', (req, res) => {...});: This line defines a GET endpoint at the URL?/kundan.app.get: This is a method provided by Express to define a route for GET requests.'/kundan': This is the URL path for the endpoint.(req, res) => {...}: This is a callback function that handles the incoming request (req) and sends a response (res).
  • res.status(200).send({...});: This line sends a response with a status code of 200 (OK) and a JSON object.res.status(200): Sets the HTTP status code to 200..send({...}): Sends a JSON object as the response.

POST Endpoint with Parameter

app.post('/kundan/:id', (req, res) => {
    const { id } = req.params;
    const { logo } = req.body;

    if (!logo) {
        return res.status(418).send({ message: 'We need a logo!' });
    }

    res.send({
        kundan: `?? with your ${logo} and ID of ${id}`,
    });
});        

  • app.post('/kundan/:id', (req, res) => {...});: This line defines a POST endpoint at the URL?/kundan/:id.app.post: This is a method provided by Express to define a route for POST requests.'/kundan/:id': This is the URL path for the endpoint.?:id?is a route parameter that can be accessed in the request.(req, res) => {...}: This is a callback function that handles the incoming request (req) and sends a response (res).
  • const { id } = req.params;: This line extracts the?id?parameter from the request URL.req.params: This object contains route parameters.{ id }: This is destructuring assignment to extract the?id?parameter.
  • const { logo } = req.body;: This line extracts the?logo?property from the request body.req.body: This object contains data sent in the request body.{ logo }: This is destructuring assignment to extract the?logo?property.
  • if (!logo) { ... }: This block checks if the?logo?property is missing from the request body.!logo: This checks if?logo?is?undefined?or?null.return res.status(418).send({ message: 'We need a logo!' });: If?logo?is missing, this line sends a response with a status code of 418 (I'm a teapot) and a message indicating that a logo is needed.
  • res.send({...});: This line sends a response with a JSON object.{ kundan:??? with your ${logo} and ID of ${id}?}: This creates a JSON object with a custom message that includes the?logo?and?id?values.

Starting the Server

app.listen(PORT, () => {
    console.log(`Server is running on https://localhost:${PORT}`);
});        

  • app.listen(PORT, () => {...});: This line starts the server and listens for requests on the specified port.app.listen: This is a method provided by Express to start the server.PORT: This is the port number on which the server will listen for requests.() => {...}: This is a callback function that runs when the server starts successfully.
  • console.log(...);: This line logs a message to the console indicating that the server is running and listening for requests on the specified port.

Running the Server

To start the server, use the following command:

node index.js        

This command runs the?index.js?file, starting the server on?https://localhost:8080.


node . will start running server on your local host

Test the GET endpoint:

curl https://localhost:8080/kundan        

Test the POST endpoint:

curl -X POST https://localhost:8080/kundan/504 -H "Content-Type: application/json" -d '{"logo": "?"}'        

  • -X POST: This specifies the HTTP method to use. In this case,?POST?is used to send data to the server.
  • https://localhost:8080/kundan/504: This is the URL of the endpoint. The path?/kundan/504?indicates:
  • /kundan: The base path of the endpoint.
  • /504: The ID parameter (in this case,?504).
  • -H "Content-Type: application/json": This sets the HTTP header?Content-Type?to?application/json, indicating that the data being sent is in JSON format.
  • -d '{"logo": "?"}': This specifies the data to send in the request body. The data is a JSON object with one property:

  • logo: The value is the string?"?".

What the Server Does with This Request

The server processes this request as follows:

  1. Route Matching: The server checks if there is a route defined for?POST /kundan/:id.
  2. Extract Parameters and Body:
  3. Logic in the Route Handler:

app.post('/kundan/:id', (req, res) => {
    const { id } = req.params;
    const { logo } = req.body;

    if (!logo) {
        return res.status(418).send({ message: 'We need a logo!' });
    }

    res.send({
        kundan: `?? with your ${logo} and ID of ${id}`,
    });
});        

  • const { id } = req.params;: Extracts the?id?parameter from the request URL. Here,?id?will be?'504'.
  • const { logo } = req.body;: Extracts the?logo?property from the request body. Here,?logo?will be?'?'.
  • Validation: The server checks if the?logo?property is provided. If not, it responds with a status code of 418 and a message. In this case,?logo?is provided, so this check is passed.
  • Response: The server sends a JSON response with the following structure:

Output of the above POST endpoint
{"kundan":"?? with your ? and ID of 504"}%        

  • {"kundan":"?? with your ? and ID of 504"}: This is the JSON response sent by the server. It contains a single property?kundan?with a value that includes the emoji???, the provided?logo?(?), and the?id?(504).
  • %: This is just the command prompt indicator that the command has finished executing. It is not part of the server's response.

In conclusion, testing APIs is essential for ensuring functionality, reliability, performance, and security. By verifying that each endpoint works as intended, handles requests appropriately, performs well under varying conditions, and remains secure against vulnerabilities, API testing guarantees a robust and dependable application interface.



要查看或添加评论,请登录

Kundan Antyakula??的更多文章

社区洞察

其他会员也浏览了