skip to Main Content

For example I have the following route for DELETE method:

DELETE /api/user/{user_id}/friends/{friend_id}

this is a POST method so it won’t be cached in the end because user_id is the logged in user session and can be obtained in the server

I can change the route to be (Which still uses parameter)

DELETE /api/user/friends/{friend_id}

or to be

DELETE /api/user/friends/

while sending the friend_id in the post request of axios

axios.delete(`/api/user/friends/`, { friend_id })

I have similar cases with PUT/PATCH too, so I was wondering what is the best approach for user-based API calls that won’t be cached?

2

Answers


  1. Route Design: If the friend relationship is directly related to the logged in user, it is good practice to include the user ID as part of the URL. In this way, you maintain structure

    DELETE /api/user/{user_id}/friends/{friend_id}
    

    Cache Control: To prevent caching of user-specific data, you can use appropriate HTTP headers to control caching behavior. For example

    Cache-Control: no-cache
    
    Login or Signup to reply.
  2. axios.delete(`/api/user/friends/`, { friend_id })
    

    Expecting useful things to happen with a request body in a DELETE request is a Bad Idea [tm]

    content received in a DELETE request has no generally defined semantics — RFC 9110

    What this request is actually telling general purpose http components is that you are trying to DELETE the /api/user/friends/ resource. That’s probably not what you want.


    In general, the target URI for a DELETE (or a PUT or a PATCH) should use the same target URI as the GET request that fetches the current representation of the resource.

    The motivation here is the uniform interface constraint of REST – we want HTTP messages to all mean the same thing, without regard to the specialization of the client or the resources on the server.

    So GET always means "get the target", and put always means "update the target", and patch always means "patch the target" and delete always means "remove the association between the target resource and its current functionality".

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search