简体   繁体   中英

Correct Rest API endpoint

Hi Im working on a REST API for a e-commerce app and had a couple questions about which are the correct URNs to map some specific actions, having in mind the definition of URI stated on RFC 3986: A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource.

  1. The action of sharing a post which receives an email and shares the post url via mail. Specific posts are mapped to /api/posts/id which is correct. The thing is I don't know how to map the URL of this action. A post to an URI like /api/posts/id/share is totally incorrect by definition of URI considering that share is an action and not a resource.
  2. The action of resetting your password and the action of asking for a password reset email. Users are mapped to /api/users. Something like /api/users/password-reset-email and /api/users/password-reset would be incorrect following the same guideline explained before.

The key takeaway from the dissertation that introduced REST is:

Any information that can be named can be a resource...

Have a look at Resources and Resource Identifiers for more information.

In other words, an action is a resource. In your own words, a URI is a sequence of characters that identifies an " abstract or physical resource". Just because an action doesn't easily map to a tangible object doesn't make it less of a resource.

There are status codes which only exist to respond to 'actions' (eg 202 Accepted ).

All in all, POST /api/posts/{id}/share seems completely reasonable.

POST is really there as a 'catch all' for actions. In RFC2616 it says the "function performed by the POST method is determined by the server" and the function performed "might not result in a resource that can be identified by a URI".

The main points:

  1. An 'action' should almost always involve POST
  2. The 'action' performed should relate to the URI and body of the POST request.
  3. You should return an appropriate status code (eg 200 , 201 , 202 , 204 , 4xx ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM