Middle
What HTTP response codes would you suggest for this API and when are they used?
sobes.tech AI
Answer from AI
The choice of HTTP response codes depends on the result of the request processing and the API context. Here are the main codes to use:
- 200 OK — successful request, returning the requested resource or operation result.
- 201 Created — when a new resource is successfully created (e.g., POST request).
- 204 No Content — successful request with no response body, such as when deleting a resource.
- 400 Bad Request — invalid request, such as missing required parameters or incorrect data format.
- 401 Unauthorized — request requires authentication or the token is invalid.
- 403 Forbidden — access is denied, even if the user is authenticated.
- 404 Not Found — the requested resource is not found.
- 409 Conflict — conflict when trying to create or modify a resource (e.g., duplicate unique field).
- 422 Unprocessable Entity — valid request, but data does not pass business validation.
- 500 Internal Server Error — server error that cannot be processed.
Example:
If the API creates a user:
- On success — 201 Created with the new user in the body.
- If data is incorrect — 400 Bad Request with an error description.
- If a user with the same email already exists — 409 Conflict.
This approach helps API clients correctly handle responses and build interaction logic.