Skip to content

Instantly share code, notes, and snippets.

@mpaltun
Last active November 20, 2017 15:26
Show Gist options
  • Save mpaltun/9521f9e9b5bad06356f82bde29d4837d to your computer and use it in GitHub Desktop.
Save mpaltun/9521f9e9b5bad06356f82bde29d4837d to your computer and use it in GitHub Desktop.
Restful API Notes

PUT

  • You are referring to an entity, not to a collection.
  • The entity you are supplying is complete (the entire entity).
  • Idempotent
  • Could be used for partial updates but need to create a new resource for every field. PUT /users/123/email, /users/123/address

PATCH

  • Partial updates
  • Not idempotent

POST

  • Create new entity
  • Not idempotent
  • POST is usually for new resource creation. It can also be used as a catch-all verb, such as a utility API request. (Utility API is different from regular resource operation. Example: validating a marketing promotion code.)

Status Codes

  • 409 for when a conflict of data exists.
  • 400 when input is malformed
  • 401 for when an access token isn’t provided, or is invalid.
  • 422 input is understood correctly but this request is semantically invalid. (Email already activated ?)
  • 403 for when an access token is valid, but requires more privileges.
  • 201 if a new resource was created in response to this request.
  • 202 if the request was accepted, but will be processed asynchronously.
  • 204 if you have no useful response entity (DELETE responses)
  • Note that these codes are intended for the API service layer, not for the business logic layer. For example, when the search result of /search?q=xyz is empty, the server should return a 200 rather than 404, because the “/search resource” exists and the request is fulfilled successfully.

Notes

  • Non-enveloped array is exploitable. OWASP recommends to always return JSON with an object on the outside.
  • Use singular for singleton resource (i.e. only one instance is possible for the client). For example, the user in GET /user/subscriptions of GitHub watching API is singular because it refers to the current authenticated user.
  • Utility API is different from resource API; any reasonable endpoint choice would be fine. For example: /search?q={keywords}.
  • 401 vs. 403: 401 means the client has not been authenticated. (The use of “Unauthorized” by the HTTP spec is somewhat misleading.) 403 means the current client (usually authenticated) or all clients are not allowed for the request.

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment