CRUD Application Using Node JS - PART 4 : Configuring the API's (Get by ID, DELETE, UPDATE) | Final Wrap Up

CRUD Application Using Node JS - PART 4 : Configuring the API's (Get by ID, DELETE, UPDATE) | Final Wrap Up

In the previous article I had shown you how to write the API's for saving the programmer details and fetch all the programmer details. Now in this article we will learn about:

  • Fetch a particular programmer with unique ID
GET : http://localhost:9000/programmer/<id>
  • Update a particular programmer with unique ID
PATCH : http://localhost:9000/programmer/<id>
  • Delete a particular programmer details
DELETE : http://localhost:9000/programmer/<id>

So, as always, we will go step-by-step. And the source code is available at the end, but don't try to scroll to bottom soon after reading this! Believe me it won't help.


1. Fetch a particular programmer with unique ID

In previous article we tried to fetch all the details of programmers at once as a array of JSON objects. Now, we will try to fetch a single programmer details using his unique ID. Because not every time we need the entire data. To do this follow these simple steps:

  1. Write a GET method using express and give a path /programmers/:id.
  2. Save the id from req object as req.params.id
  3. Use the method .findById(id) from our Programmer object.
  4. Save the response in a variable and send the response back as JSON.
  • So, the first step is to write GET method:
app.get('/programmer/:id',(req,res)=>{
    // write the logic here    
})
  • The next step is save id from req object
app.get('/programmer/:id',(req,res)=>{
    const id = req.params.id
    const programmer
    // write the logic here    
})

Here :id represents a path variable, and we can access it from req.params object.

  • Next up, we need to use the method .findById(id)
app.get('/programmer/:id', async (req, res) => {
    var id = req.params.id
    let programmer = ''
    try {
        programmer = await Programmer.findById(id) //fetching by ID
        if (programmer == null) { // checking for null values
            return res.status(404).json({ message: 'Cannot find programmer' })
        }
    } catch (err) {
        return res.status(500).json({ message: err.message })
    }

    res.send(programmer) //sending the response

})

As we have to use the same functionality in the next step, that is update a user using ID, we will modularize this code a little bit by writing a separate method getProgrammer and call it in the above GET call. After doing the refactoring, the code will look like this:

// Getting one by ID

app.get('/programmer/:id', getProgrammer, (req, res) => {

    res.send(res.programmer)

})

// re-usable code logic
async function getProgrammer(req, res, next) {
    var id = req.params.id
    console.log(id);
    let programmer = ''
    try {
        programmer = await Programmer.findById(id)
        if (programmer == null) {
            return res.status(404).json({ message: 'Cannot find programmer' })
        }
    } catch (err) {
        return res.status(500).json({ message: err.message })
    }
    res.programmer = programmer
    next()
}

next() is used to pass on the control to the next method.

Now we have done it, lets try to hit the http://localhost:9000/programmer/<id> API endpoint in postman:

image.png

As you can see in above image, w have passed 604f0b9cfcb2383ab47c1fa8 as ID, and we got the result.

2. Update a particular programmer with unique ID

There will be a situation where we need to edit someone's details after saving it. So, I will show you how to edit a programmer's data using ID as before. We use PATCH http protocol. Follow these steps to do that:

  1. Create a PATCH method using express() framework on the path /programmer/:id
  2. Get the existing programmer and save it in a variable. (call getProgrammer method)
  3. Modify that response with user input req object.
  4. Save it in the database using .save() method.
  • In the first step, we have oto write a PATCH method:
// Updating One
app.patch('programmer/:id', async (req, res) => {
  // write logic here
})
  • Now, we need to get the existing user details, that is to call the re-usable getProgrammer method

// Updating One
app.patch('/:id', getProgrammer, async (req, res) => {
    let exitingProgrammer = res.programmer
})
  • Check the user input response and assign them to the existing details
app.patch('/programmer/:id', getProgrammer, async (req, res) => {
    let existingProgrammer = res.programmer

    if(req.body.name !== null){
        existingProgrammer.name = req.body.name
    }
    if(req.body.age !== null){
        existingProgrammer.age = req.body.age
    }
    if(req.body.skill !== null){
        existingProgrammer.skill = req.body.skill
    }
    if(req.body.hasJob !== null){
        existingProgrammer.hasJob = req.body.hasJob
    }
})
  • Save it in the database
// Updating One
app.patch('/programmer/:id', getProgrammer, async (req, res) => {
    let existingProgrammer = res.programmer 
    if(req.body.name !== null){
        existingProgrammer.name = req.body.name
    }
    if(req.body.age !== null){
        existingProgrammer.age = req.body.age
    }
    if(req.body.skill !== null){
        existingProgrammer.skill = req.body.skill
    }
    if(req.body.hasJob !== null){
        existingProgrammer.hasJob = req.body.hasJob
    }

    try {
    const updatedProgrammer = await res.programmer.save() //saving in DB
    res.send(updatedProgrammer) // sending back as response
  } catch (err) {
    res.status(400).json({ message: err.message })
  }
})

Now we will test this to a user of id 604f0b9cfcb2383ab47c1fa8 and a request body

{
    "name": "Sai Charan Devalla",
    "age": "25",
    "skill": "Angular, JavaScript, NodeJS",
    "hasJob": true
}

The original Object before update:

{
    "_id": "604f0b9cfcb2383ab47c1fa8",
    "name": "Sai Charan",
    "age": 23,
    "skill": "Angular, JavaScript",
    "hasJob": true,
    "__v": 0
}

image.png

As you can see, the response has modified after updating it.

4. Delete a particular programmer details

The final API in our list is Deleting a record from database. In order to do that, follow these steps:

  1. Write a DELETE method using express() and give a path programmer/:id
  2. Retrieve the existing user using its ID (Use the existing getProgrammer method)
  3. Use .remove() method to delete the data.

  4. Write a DELETE method using:

app.delete('/programmer/:id', async (req, res) => {
    // write the code
})
  • Retrieve the existing user and save it
app.delete('/programmer/:id', getProgrammer, async (req, res) => {
    // write the code
})
  • Use .remove() method to delete the data.
//Delete 
app.delete('/programmer/:id', getProgrammer, async (req, res) => {
    try {
        await res.programmer.remove()
        res.json({ message: 'Deleted Subscriber' })
    } catch (err) {
        res.status(500).json({ message: err.message })
    }
})

After running the above code with the ID 604f0b9cfcb2383ab47c1fa8 and we can able to delete it successfully as shown in the below picture.

image.png


Conclusion

Yay! Finally we came to an end of the entire series. I personally learned lot of basics in Nodejs on how to write CRUD API's which are basic bare bones of a server language like nodejs. Before starting this series, I didn't know anything about nodejs, believe me.

Anyway, hope you learned some basics of nodejs through my tutorial. Feel free to express your doubts, views or anything you like to mention. If you find this series useful, please share it to your friends so that they can also learn.

You can find the source code in GitHub

Also you can find this entire series here : Getting hands dirty with NodeJS - CRUD REST API using Node | Express | MongoDB

Thanks!

Did you find this article valuable?

Support Devalla Sai Charan by becoming a sponsor. Any amount is appreciated!