How To Build REST Api using Express(Node.js).......?PART-2

Hello World,

We had covered GET and POST method in previous part now we are going to see the PUT and DELETE method.

3.PUT-Method is used for updating the content or modified the content.

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

let my_data=[{
                id:1,
                name:"xyz"
},
{
               id:2,
               name:"mnl"
}]

here we are going to modify the my_data of id 1 using put request ,for that we need endpoint and id of object which we need to update.Here we also going to use postman for testing our app,and for simplicity i am not going to implement any validation logic.

In following code first we need to find the document by applying filter method then find index of document and then we will update it.

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

let my_data=[{
                id:1,
                name:"xyz"
},
{
               id:2,
               name:"mnl"
}]


app.put('/api/data/:id',(req,res)=>{

    const n=my_data.filter(item=>item.id==req.params.id)
    const index=my_data.indexOf(n[0])
    console.log(index)
    my_data[index].name=req.body.name
   res.send(my_data)

})


app.listen(3001,()=>{
console.log("server is running on port 3001......")
})

then open postman and choose PUT method add endpoint with id and in body section add new name

blog1.png

then just click on send button you will get the response with updated document.

blog2.png

4.DELETE - Method used for delete the content of document.

for deletion there is need to specify the id of content which we going to delete

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

let my_data=[{
                id:1,
                name:"xyz"
},
{
               id:2,
               name:"mnl"
}]


app.put('/api/data/:id',(req,res)=>{

    const n=my_data.filter(item=>item.id==req.params.id)
    const index=my_data.indexOf(n[0])
    console.log(index)
    my_data[index].name=req.body.name
    res.send(my_data)

})
app.delete("/api/data/:id",(req,res)=>{
    const afterD=my_data.filter(item=>item.id!=req.params.id)
    my_data=[...afterD]
    res.send(my_data)
})

app.listen(3001,()=>{
console.log("server is running on port 3001......")
})

then open postman choose delete method ,add endpoint with id and hit send button and boom you succesfully deleted the content of document.

thank u