TL;DR
When designing a (JSON) API, pay extra attention to HTTP statuses used. I usually refer to Rails status cheat-sheet.
Quick tips:
- For
201 :created
prefer no body, just a HEAD response. - Be on top of your 4** code use
-
401 :unauthorized
(actually "unauthenticated") if no session/token to identify 'user'. Use response body to specify details (no token, expired token, invalid token etc.) -
403 :forbidden
if user is known, but lacks permissions to interact with the resource. Use response body for details about resource and lacking permission. -
400 :bad_request
if something off with params or format etc. I use this if, for example, filtering params are wrong, page size is exceeded and other meta-probems. Use response body to explain the problem. -
422 :unprocessable_entity
for generic validation errors where user should review submitted data and try again. Think extra hard about how to standardize the response so that you can inform the user about the exact (possibly nested, array) field that is problematic. "Dig" string a-la"data", "users", 0, "email"
is useful to specify the "path" inside the submitted structure.
-
The story
Today I was struggling with legacy API comms.
The logic was simple
if response.code.between?(200, 299)
yay_success
else
...
But responses like
{"success":false, "message":"ERR: No vendor found for ABC"}
and even
{"success":true, "message":"ERR: No item found for 123"}
were naturally tripping us up, because apparently parsing the response JSON is now also necessary. This is further complexed by lack of docs and consistency, some endpoints respond with "OK", which is not valid JSON, sigh.
It would be really nice, if responses of problems of this kind were not of the 2** group, but a 422 or somesuch. In that case knowledge and parsing issues for the body become irrelevant, things become slef-documenting™, yada, yada.
Top comments (0)