Skip to main content

USE Delete action to delete a single resource

When deleting a single resource in a RESTful API, it is recommended to use the DELETE method. Unlike other methods that modify the resource, the DELETE method removes the entire resource.

Using the DELETE method to delete a single resource can be particularly useful in situations where you want to remove the resource completely from the server, or when you want to avoid having unused data in the database. For example, if you have a user profile resource that is no longer needed, you could use DELETE to remove it from the server.

To implement the DELETE method for a resource in your API, you should define a corresponding endpoint in your controller. The endpoint should accept the ID of the resource to be deleted as a parameter in the route and should return an appropriate response code indicating the status of the operation.

While the code block below seems very simple, there are a few constraints that need to be followed while developing a delete endpoint. Let's follow what's been done in this example from a UsersController:

  • Name your method as DeleteUser
  • Get ID from route that's defined in [HttpDelete("{id}")]
  • Place appropriate ProducesResponseType attributes for each return type
  • Return 204 if there are no errors
  • Never return 404 for delete operations as HTTP DELETE is idempotent and if there is no resource at given location than it's considered deleted
  • Return ProblemDetails for errors
[HttpDelete("{id}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
public async Task<IActionResult> DeleteUser([FromRoute] long id)
{
return NoContent();
}

Never implement custom methods other than described 6 actions (Query, Get, Create, Update, Patch, Delete).