REST API Delete Resource

REST API Delete Resource

In this article we will look at REST API Delete operation. Compared to Create and Update, Delete operation is fairly easy and straightforward.

REST API Delete Implementation

Below, we will outline the basic steps of Delete operation implementation. Please, watch our video for more in depth explanation of this concept.

Route and Controller

In routes/v1/travels folder in index.ts file let’s create a REST API Delete route. It will use controller’s detletTravel function.

travels.delete("/:id", deleteTravel);

Now let’s create that deleteTravel function in controller.ts file.

export const deleteTravel = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  try {
    const repository = new TravelRepository();
    await repository.delete(req.params.id);
    res.status(204).send();
  } catch (error) {
    next(error);
  }
};

The function instantiates TravelRepository and calls delete method on it with the id passed in the request. If successful, the function returns 204 response without a body. If there’s an error, catch block kicks in and passes the error to ErrorHandler via next function.

Repository

In BaseRepository.ts file let’s create delete method.

async delete(id: string): Promise<A> {
    const instance = await this.modelClass.findByPk(id);
    if (!instance) {
      throw new ApiError({
        name: "NOT_FOUND_ERROR",
        message: "Entity not found",
        status: 404,
        code: "ERR_NF",
      });
    }
    return instance.destroy();
  }

Similarly to update method, delete method attempts to find an instance of Travel by id. If the instance is not found, unlike update method, delete method throws Not Found API error, since the controller’s delete function doesn’t use the resource. The error will be caught and handled by the ErrorHandler. If there’s an instance, delete method calls destroy on the instance deleting the record from the database.

Conclusion

And here it is. We created a method to delete a resource in Node.js API project. Together with Read, Create and Updated REST API Delete resource operation plays the essential role in crafting efficient and reliable web services.

Resources

Git Repository

Share this article

Similar Posts