BIS601 Program 7

7. Install Express (npm install express). Set up a basic server that responds with “Hello, Express!” at the root endpoint (GET /). Create a REST API. Implement endpoints for a Product resource: GET : Returns a list of products. POST: Adds a new product. GET /:id: Returns details of a specific product. PUT /:id: Updates an existing product. DELETE /:id: Deletes a product. Add middleware to log requests to the console. Use express.json() to parse incoming JSON payloads.

Step 1: Create Project

  • Create a folder and open with vscode.
  • Open integrated vscode terminal.

Step 2: Install Express:

  • Execute one by one below command.
mkdir express-api

cd express-api

npm init -y

npm install express

Step 3: Create server.js

  • Create server.js file inside the express-api folder. Right click on the express-api folder and create file server.js.
  • After then copy the below code and paste it in that server.js file, save it.
const express = require('express');
const app = express();

// Middleware to log requests to the console
app.use((req, res, next) => {
    console.log(`${req.method} request made to: ${req.url}`);
    next();
});

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

// Root endpoint to return "Hello, Express!"
app.get('/', (req, res) => {
    res.send('Hello, Express!');
});

// Sample in-memory data for products
let products = [
    { id: 1, name: 'Laptop', price: 1000 },
    { id: 2, name: 'Phone', price: 500 }
];

// GET /products: Returns a list of all products
app.get('/products', (req, res) => {
    res.json(products);
});

// POST /products: Adds a new product
app.post('/products', (req, res) => {
    const { name, price } = req.body;
    if (!name || !price) {
        return res.status(400).json({ message: 'Name and price are required' });
    }
    const newProduct = { id: products.length + 1, name, price };
    products.push(newProduct);
    res.status(201).json(newProduct);
});

// GET /products/:id: Returns details of a specific product
app.get('/products/:id', (req, res) => {
    const product = products.find(p => p.id === parseInt(req.params.id));
    if (!product) {
        return res.status(404).json({ message: 'Product not found' });
    }
    res.json(product);
});

// PUT /products/:id: Updates an existing product
app.put('/products/:id', (req, res) => {
    const product = products.find(p => p.id === parseInt(req.params.id));
    if (!product) {
        return res.status(404).json({ message: 'Product not found' });
    }
    const { name, price } = req.body;
    if (!name || !price) {
        return res.status(400).json({ message: 'Name and price are required' });
    }
    product.name = name;
    product.price = price;
    res.json(product);
});

// DELETE /products/:id: Deletes a product
app.delete('/products/:id', (req, res) => {
    const productIndex = products.findIndex(p => p.id === parseInt(req.params.id));
    if (productIndex === -1) {
        return res.status(404).json({ message: 'Product not found' });
    }
    products.splice(productIndex, 1);
    res.status(204).send();
});

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

Step 4: Download and Install Postman:

  • Visit the Postman download page:
  • Download Postman:
    • Click on the “Download” button for Windows (or your respective operating system). The website will automatically detect your OS.
  • Run the installer:
    • Once the download is complete, open the .exe file to begin the installation process.
    • Follow the on-screen instructions to install Postman.
  • Launch Postman:
    • After installation, you can launch Postman from your desktop or Start Menu.
  • Create a Postman Account (Optional)
    • Sign up for a Postman account:
      • Once Postman is installed, open the application. You can sign up for a free Postman account or continue using Postman without an account. Signing up will allow you to sync collections across devices, but it is optional.

Step 5: Run the Server:

  • Run the server using below command. It will start server to communicate with the postman.
node server.js
output server.js

Step 6: Open Postman:

  • Once your server is up and running, follow these steps to test the various endpoints.

Step 7: Create a New Request:

  • Open Postman.
  • Click on the New button on the top left, then select Http from the options.
  • Enter url as per screenshot or generated on the terminal while running server.
  • Click on send button and then you will get output hello express as per screenshot.
Create a New Request
Screenshot 566

Step 8: Test Fetching All Products: GET /products

  • Steps to Test:
    • Again follow step 7 and this time Choose Method: GET and the url is http://localhost:3000/products
    • Then click on send button to see the output of the all product.
Test Fetching All Products: GET /products

Step 9: Test Adding a New Product: POST /products

  • Steps to Test:
    • Again follow step 7 and this time Choose Method: POST and the url is http://localhost:3000/products
    • Then click on send button you can see message like “message”: “Name and price are required”
    • Go to the Body tab in Postman.
    • Select raw and choose JSON from the dropdown.
    • Enter the following JSON data:
{
  "id": 3,
  "name": "Tablet",
  "price": 300
}
Test Adding a New Product: POST /products

Step 10: Test Fetching a Specific Product: GET /products/:id

Test Fetching a Specific Product: GET /products/:id

    Step 11: Test Updating a Product: PUT /products/:id

    • Steps to Test:
      • Method: PUT
      • URL: http://localhost:3000/products/1 (replace 1 with the ID of the product you want to update)
      • Go to the Body tab in Postman.
      • Select raw and choose JSON from the dropdown.
    • Enter the following JSON data:
    {
      "id": 1,
      "name": "Updated Laptop",
      "price": 1100
    }
    Test Updating a Product: PUT /products/:id

    Step 12: Test Deleting a Product: DELETE /products/:id

    • Steps to Test:
      • Method: DELETE
      • URL: http://localhost:3000/products/1 (replace 1 with the ID of the product you want to delete)
      • Click Send.
      • Expected Response:
      • You should get a 204 No Content response, indicating that the product has been deleted successfully.
    Test Deleting a Product: DELETE /products/:id
    guest
    0 Comments
    Inline Feedbacks
    View all comments
    0
    Would love your thoughts, please comment.x
    ()
    x