how to start writing API request

ehdtlaos

Edrick Ee

Posted on August 14, 2021

how to start writing API request

In order to request data from API, we need to set up an express to do get request

  1. npm install express

  2. create file name index.js for my main server foler

  3. const express = require('express')
    to call express

  4. const db = require('../databasefolder')
    call db folder & file

  5. start express by writing
    const app = express();
    const port = 1004;

port can be any 4 digit numbers

  1. app.listen(port, () => console.log(Successfully connected to the port ${port}))

  2. write your get, put, post requests

ex.

app.get('/products', (req, res) => {
  let { page, count } = req.query;
  if (page === undefined) {
    page = 0;
  };
  if (count === undefined) {
    count = 5;
  };
  db.getProducts(page, count, (err, result) => {
    if (err) {
      res.status(400)
      console.log(err);
    }
    res.status(200)
    res.send(result);
  })
});

app.get('/products/:product_id', (req, res) => {
  const { product_id } = req.params;
  db.getCurrentProduct(product_id, (err, result) => {
    if (err) {
      res.status(400)
      console.log(err);
    }
    res.status(200)
    res.send(result);
  })
});
Enter fullscreen mode Exit fullscreen mode
đź’– đź’Ş đź™… đźš©
ehdtlaos
Edrick Ee

Posted on August 14, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related