Sunday, April 19, 2020

RESTful API with PUT and DELETE requests


3. Handling PUT Request
Index.js: Update code in the Index.js for PUT Request: 

// PUT Request
app.put('/api/courses/:id', (reqres=> {

  // look for the course (Copy the code of app.get('/api/courses'))
  // if not existing, return 404-resourse not found
  const course = courses.find((c=> c.id === parseInt(req.params.id));
  if (!courseres.status(404).send('Course with given id not found ');
  res.send(course);

  // validate (copy code from app.post('/api/courses'))
  // if invalid, return 400 - bad request
  const schema = {
    name: Joi.string().min(3).required(),
  };
  const result = Joi.validate(req.bodyschema);
  if (result.error) {
    res.status(400).send(result.error.details[0].message);
    return;
  }

  // update course
  // return update course to client
  course.name = req.body.name;
  res.send(course);
});

Output: To Execute PUT request, again we use POSTMAN tool with PUT request option.




4. Handling DELETE Request

Index.js: Update code in the Index.js for DELETE Request: 

// Delete Request
app.delete('/api/courses/:id', (reqres=> {
  // look for the course (Copy the code of app.get('/api/courses'))
  // if not existing, return 404-resourse not found
  const course = courses.find((c=> c.id === parseInt(req.params.id));
  if (!coursereturn res.status(404).send('Course with given id not found ');
  res.send(course);

  // delete course
  const index = courses.indexOf(course);
  courses.splice(index1);

  // return deleted course to client
  res.send(course);
});

Output: To Execute DELETE request, we use POSTMAN tool with DELETE request option