What is a best practice for REST API response structure and layout?
Example of scrath:
Success response:
{
"status": "success",
"data": # some data here
}
Fail response:
{
"status": "fail",
"data": {
"code": # some error code,
"message": # some error explaining message
}
}
The simplest way we handle errors is to respond with an appropriate status code. Here are some common response codes: 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter. 401 Unauthorized – client failed to authenticate with the server.
The API should always return sensible HTTP status codes. API errors typically break down into 2 types: 400 series status codes for client issues & 500 series status codes for server issues. At a minimum, the API should standardize that all 400 series errors come with consumable JSON error representation.
Generally, APIs that are considered high-performing have an average response time between 0.1 and one second. At this speed, end users will likely not experience any interruption. At around one to two seconds, users begin to notice some delay.
When you send a REST request, the appliance responds with a structured response in JSON format. The exact structure of the response depends on the resource and URI of the request, but all responses are similar. The response includes all available resources from any point within the API.
There is many ways to design you API response. It is conditional to your architecture, technology, and other aspects.
Based on your example, I would respond this way
Successful request:
{ "status": "success", "data": { /* Application-specific data would go here. */ }, "message": null /* Or optional success message */ }
Failed request:
{ "status": "error", "code": 404, "data": null, /* or optional error payload */ "message": "Error xyz has occurred" }
For more info about this topic take a look at this links
Standard JSON API response format?
Best Practices for Designing a Pragmatic RESTful API
REST API Error Codes 101
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With