Writing Your First REST API

code.jpg

REST API

so this is the second part to my previous post 'Understanding REST api',in this part we'll make a small REST - API in node JS. so without further ado let's start making your first ever API

TOOLS

  1. install node js (nodejs.org)
  2. install vs code (editor)
  3. install POSTMAN (for testing routes)

Steps

  • create a folder
  • initialize the folder with
    npm init -y
    
  • open the folder in vscode
  • type ctrl+shift+` in your keyboard to open integrated terminal
  • we'll be using expressjs for writing api
  • so in terminal type npm install express uuid
  • uuid will help us to create a RFC random id
  • in package.json go to scripts and replace tests with
    "scripts":{
      "start":"node app.js"
    }
    

LET'S start

create a file called app.js in your root folder inside app.js write the following code

// requiring express
const express = require("express");
// all the custom routes of API
const routes = require("./routes/routes");
const PORT = process.env.PORT || 2002;

// intialize app instance
const app = express();

app.use(express.json());
// using routes from routes.js file
app.use("/", routes);

// make our app listen to port 2002 , so it will serve resources there

app.listen(PORT, () => {
  console.log(`app is running on port ${PORT}`);
});

all of our routes are stores in folder called routes/routes.js inside routes.js write the following code

// get the router from express
const router = require("express").Router();
const uuid = require("uuid");

// add an array as a custom resource

// @uuid.v4() generates random id
let songs = [
  { id: uuid.v4(), name: "Dil to pagal hai", year: 2005 },
  {
    id: uuid.v4(),
    name: "Dilbaro",
    title: 2018,
  },
  {
    id: uuid.v4(),
    name: "Sakhi by shankar mahadevan",
    year: 2020,
  },
];

// @Get Request for getting all the songs , so whenever this route is
// requested this callback will be executed and we're returning songs data in 
// json
router.get("/api/v1/getallsongs", (req, res) => {
  res.json(songs);
});

// @get the particular song , by passing id as a parameter in request , you
//see :id here which is placeholder for a parameter

router.get("/api/v1/song/:id", (req, res) => {
 // using find method to find particular song
 let song = songs.find((song) => song.id === req.params.id);
  if (song) {
    res.json(song);
  } else {
    res.json({ msg: "no song found" });
  }
});

// @Post Request - receive request with body (contains data)
// and insert a new song in array
router.post("/api/v1/addsong", (req, res) => {
  const { name, year } = req.body;
  songs.push({ id: uuid.v4(), name, year });
  res.json({ msg: "song added" });
});


// @Delete Request - we're passing id of a song in :id as a parameter in
// request
router.delete("/api/v1/delete/:id", (req, res) => {
  //filter the song by id
  songs = songs.filter((song) => song.id !== req.params.id);
  res.json(songs);
});

module.exports = router;

how to check whether request working or not? open the postman , if you want a get request ,select GET from a dropdown , and type endpoint in url section

you can checkout the code at : github.com/WhoAdarshPandya/rest_for_beginners

in upcoming blogs , we'll cover how to deploy a complete rest api on heroku :)