Setup your custom API source for Postman testing

custom API source for Postman testing

Instead of searching for public API sources that you could test for practicing purposes, why wouldn’t you just create your own source? It isn’t that hard at all. Of course, you gotta have some basic development knowledge, but really basic.

Here are the steps that you should follow in order to setup the environment to run your local server with your custom API code:

  • First, make sure that you have Visual Studio Code and Node.js installed.
  • Start the setup of the project by creating a project folder inside Visual Studio Code.
  • Open the terminal in VS Code (Ctrl + ~) and run:
    npm init -y
    This creates a package.json file.
  • Install Express:
    npm install express
  • Create a Server file named for example: server.js.
  • Paste the Express server code that I will provide later below into this file.
  • Run the server:
    node server.js
  • Open the local server in the browser:
    http://localhost:3002
  • After the server is running live, you can start testing it in Postman.

Express Server code:

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

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

// Mock data
let books = [
    {
       "id": 1,
       "name": "True Love",
       "type": "non-fiction",
       "available": false
    },
    {
       "id": 5,
       "name": "Real Trouble",
       "type": "fiction",
       "available": true
    },
    {
       "id": 8,
       "name": "CSI Miami",
       "type": "fiction",
       "available": true
    }
];

// GET request
app.get("/", (req, res) => {
    console.log('GET request received.');
    res.status(200).json(books);
});

// POST request
app.post("/update", (req, res) => {
    const updates = Array.isArray(req.body) ? req.body : [req.body]; // Normalize input to an array

    const updatedBooks = [];
    const addedBooks = [];

    updates.forEach(update => {
        const { id, name, type, available } = update;

        // Validation: Ensure an ID is provided
        if (id === undefined) {
            return res.status(400).json({
                message: "ID is required to add or update a book."
            });
        }

        // Find the book by ID
        const bookIndex = books.findIndex(book => book.id === id);

        if (bookIndex !== -1) {
            // Book exists: update its properties
            if (name !== undefined) books[bookIndex].name = name;
            if (type !== undefined) books[bookIndex].type = type;
            if (available !== undefined) books[bookIndex].available = available;

            updatedBooks.push({ ...books[bookIndex] });
        } else {
            // Book doesn't exist: add it as a new book
            const newBook = { id, name, type, available };
            books.push(newBook);
            addedBooks.push(newBook);
        }
    });

    res.status(200).json({
        message: "Books processed successfully",
        updatedBooks: updatedBooks.length > 0 ? updatedBooks : undefined,
        addedBooks: addedBooks.length > 0 ? addedBooks : undefined
    });
});

// PUT request to update book data
app.put("/update/:id", (req, res) => {
    const bookId = parseInt(req.params.id); // Extract book ID from URL
    const { name, type, available } = req.body;

    // Find the book by ID
    const book = books.find(book => book.id === bookId);

    if (book) {
        // Update book properties if provided
        if (name !== undefined) book.name = name;
        if (type !== undefined) book.type = type;
        if (available !== undefined) book.available = available;

        res.status(200).json({
            message: "Book updated successfully",
            updatedBook: book
        });
    } else {
        res.status(404).json({
            message: "Book not found"
        });
    }
});

// DELETE request to remove a book by ID
app.delete("/delete/:id", (req, res) => {
    const bookId = parseInt(req.params.id); // Extract book ID from URL

    // Find the index of the book
    const bookIndex = books.findIndex(book => book.id === bookId);

    if (bookIndex !== -1) {
        // Remove the book from the array
        const deletedBook = books.splice(bookIndex, 1);

        res.status(200).json({
            message: "Book deleted successfully",
            deletedBook: deletedBook[0]
        });
    } else {
        res.status(404).json({
            message: "Book not found"
        });
    }
});

// Start server
app.listen(3002, () => {
    console.log('Server running on port 3002');
});


GET Request: Fetch All Books

  • URL: http://localhost:3002/
  • Method: GET
  • Response: JSON array of books.

The GET Response should look like this:

[
    {
       "id": 1,
       "name": "True Love",
       "type": "non-fiction",
       "available": false
    },
    {
       "id": 5,
       "name": "Real Trouble",
       "type": "fiction",
       "available": true
    },
    {
       "id": 8,
       "name": "CSI Miami",
       "type": "fiction",
       "available": true
    }
]

POST Request: Update a Book (by ID)

  • URL: http://localhost:3002/update
  • Method: POST
  • Request Body (JSON – Object):
{
    "id": 1,
    "name": "New Love Story",
    "type": "fiction",
    "available": true
}
  • Or Request Body (JSON – Array):
[
    {
       "id": 1,
       "name": "True Love",
       "type": "non-fiction",
       "available": false
    },
    {
       "id": 5,
       "name": "Real Trouble",
       "type": "fiction",
       "available": true
    },
    {
       "id": 8,
       "name": "CSI Miami",
       "type": "fiction",
       "available": true
    }
]

For example, you may want to make the first request in your collection to be a POST request with the body containing the default array with default objects, so that way you make sure that all of the necesarry items are there whenever you begin your test (maybe some got changed or deleted during the previous test).

The POST Response should look like this:

{
    "message": "Book updated successfully",
    "updatedBook": {
        "id": 1,
        "name": "New Love Story",
        "type": "fiction",
        "available": true
    }
}

In case some new items are added to an existing array the response should look something like this:

{
    "message": "Books processed successfully",
    "updatedBooks": [
        {
            "id": 5,
            "name": "Real Trouble",
            "type": "fiction",
            "available": true
        },
        {
            "id": 8,
            "name": "CSI Miami",
            "type": "fiction",
            "available": true
        }
    ],
    "addedBooks": [
        {
            "id": 1,
            "name": "True Love",
            "type": "non-fiction",
            "available": false
        }
    ]
}

PUT Request: Update a Book by ID in URL

  • URL: http://localhost:3002/update/1
  • Method: PUT
  • Request Body (JSON):
{
    "name": "Updated Book Name",
    "available": false
}

The PUT Response should look like this:

{
    "message": "Book updated successfully",
    "updatedBook": {
        "id": 1,
        "name": "Updated Book Name",
        "type": "non-fiction",
        "available": false
    }
}

DELETE Request: Delete a Book by ID

  • URL: http://localhost:3002/delete/1
  • Method: DELETE
  • Response:
{
"message": "Book deleted successfully",
"deletedBook": {
"id": 1,
"name": "True Love",
"type": "non-fiction",
"available": false
}
}

Scroll to Top