Recently I was asked to create a REST Web Service using Yii2 Framework. Here are some tips following my research on the topic:
- when working with lists we need to provide filtering, ordering and pagination. The best approach is to use query string for parameters (thus avoiding specific URIs or headers)
- status codes: 1xx: informational, 2xx: success, 3xx: redirection, 4xx: client error and 5xx: server error.
- 200 OK: the server got the request and responded accordingly. 201 Created: a new resource has been created; you should return this code when handling a POST action on a collection, for instance.
- 202 Accepted: the request has been accepted but not processed; it is queued for execution and might not be fulfilled. You can use this code when a request generates an action that will happen asynchronously, like a data update or an email.
- 204 No Content: the request was processed but the server does not have any content to return. You can use this code when handling DELETE requests.
- 301 Moved Permanently: the URL changed permanently and it can be found elsewhere.
- 302 Found & 303 See Other: the URL changed temporarily and can be found elsewhere.
- 304 Not Modified: use this code to implement caching systems. If the request headers If-Modified-Since or If-None-Match are used and the server does not have a newer version to provide, then return 304 so that the client can use the copy it has stored locally.
- 400 Bad Request: the request is malformed. Use this code to tell the client to re-send the information correcting the format issue.
- 401 Unauthorized: the user is unauthenticated and cannot be granted access to a restricted resource. Logging into the system will solve this error.
- 403 Forbidden: the user is authenticated but her cannot access this resource. Logging into the system will not change this error.
- 404 Not Found: as it sounds, probably the most well-known error code on the Internet.
- 405 Method Not Allowed: use this code when the client requests an HTTP verb that the given resource cannot handle, like POST on individual resources or PUT on collections.
- 415 Unsupported Media Type: use this code when the content type used or requested by the client is not supported by your API, like JSON when you would expect XML.
- 500 Internal Server Error: an unexpected error prevented the server from returning a response.
- 503 Service Unavailable: the server is temporarily unavailable because it’s overloaded or due to maintenance reasons.
- add an error id to track it for future reference
- once an API is made public, it should not change: its endpoints and response data structures should be consistent in time
- use plurals for resources
- HTTP methods: GET for fetching data, POST for adding data, PUT for updating data (as a whole object), PATCH for updating data (with partial information for the object), DELETE for deleting data.