Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:
- JSON API - JSON API covers creating and updating resources as well, not just responses.
- JSend - Simple and probably what you are already doing.
- OData JSON Protocol - Very complicated.
- HAL - Like OData but aiming to be HATEOAS like.
There are also JSON API description formats:
- Swagger
- JSON Schema (used by swagger but you could use it stand alone)
- WADL in JSON
- RAML
- HAL because HATEOAS in theory is self describing.
Yes there are a couple of standards (albeit some liberties on the definition of standard) that have emerged:
- JSON API - JSON API covers creating and updating resources as well, not just responses.
- JSend - Simple and probably what you are already doing.
- OData JSON Protocol - Very complicated.
- HAL - Like OData but aiming to be HATEOAS like.
There are also JSON API description formats:
- Swagger
- JSON Schema (used by swagger but you could use it stand alone)
- WADL in JSON
- RAML
- HAL because HATEOAS in theory is self describing.
Google JSON guide
Success response return data
{
"data": {
"id": 1001,
"name": "Wing"
}
}
Error response return error
{
"error": {
"code": 404,
"message": "ID not found"
}
}
and if your client is JS, you can use if ("error" in response) {} to check if there is an error.
Videos
A few potential reasons why you may wish to do this are:
the fact that some HTTP clients treat anything other than 2xx as an "exception" to be thrown, which can hide differences between transport errors (like no connection, invalid firewall, invalid endpoint/URL, etc.) and actual API errors (bad API key, request validation rules, etc.), which could both end up being thrown as errors, which leads to extra work in determining which it was and extracting the actual API error text
responses that aren't accurately / completely represented by normal status code, or even multi action requests, where you have >1 API action in a single HTTP request and each one may succeed or fail individually, in which case either a 2xx or 4xx would not be accurate
I personally prefer to inspect the JSON for errors instead of hoping that the language I'm using will easily differentiate between different kinds of errors. Java and C# for example would allow me to do multiple different catches of specific exceptions on a single try, but in JavaScript where anything can be an error and each try only allows a single catch, it's messier to separate transport errors from API errors
Many people take HTTP status code as “successful communication with the server”.
Now if a customer wants to buy a US$200 item and has only US$100 in their account, the JSON response will be “failure, insufficient funds”. But as far as HTTP is concerned, everything went just fine: It delivered a purchase order, and successfully returned back to the caller that the purchase failed.
So you get a status 200. You would get something in the 400 range if there was actually some communication failure. In that case you have no idea if there is money in the account or not. We didn’t get that far.
Note there are situations where we don’t even get an HTTP status: if the server is down, or if HTTPS negotiation fails, your application didn’t even manage to reach the server.
I noticed you've used the tag REST, so I assume you are thinking about a RESTful API implementation and have some knowledge about RESTful API design.
If you need some best practices, a couple of them I think are useful. here and here.
Looking at your examples, I would prefer the second option, the reasons are:
IsErrorcan be determined by the HTTP response, e.g. 400, 500, 200, 201, so it's redundant.StatusandMessageare also redundant when the response is successful but could be useful in an error state, like in ASP.NET, you can use the ProblemDetails response (you can customize the way you want).
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "Unable to create a new user due to missing name",
"status": 400,
"traceId": "00-0aa7d64ad154a1e1853c413a0def982d-195d3558c90f7876-00"
}
versionis an interesting one. Usually, it can be included in the request header or URL. If the API cannot handle the version requested, then it should return an error in the problem details.
Thus, I prefer the second option and send a problem details response when there is an error.
An open source CRM with more than 18K start on github uses Laravel-default api resource Project Link Code Example link
Pay attention to status codes Reference
This one is super important. If there's one thing you need to remember from this article, this is probably it:
The worst thing your API could do is return an error response with a 200 OK status code.
It's simply bad semantics. Instead, return a meaningful status code that correctly describes the type of error.
Still, you might wonder, "But I'm sending error details in the response body as you recommended, so what's wrong with that?"
Let me tell you a story.
I once had to use an API that returned 200 OK for every response and indicated whether the request had succeeded via a status field:
{
"status": "success",
"data": {}
}
So even though the status was 200 OK, I could not be absolutely sure it didn't fail to process my request.
This kind of design is a real no-no because it breaks the trust between the API and their users. You come to fear that the API could be lying to you.
All of this is extremely un-RESTful. What should you do instead?
Make use of the status code and only use the response body to provide error details.
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "Expected at least two items in list."
}
Hi guys, I'm working on Spring Boot project, also this question can be ask for any backend app. I'm trying to figure out which REST API Response format is better. I have done some research but still, I need the opinion from the community. Which approach would you suggest in terms of best practice, code quality, maintainability and readability?P/s: If you guys have other suggestion, would love to read that.
Option 1:
// Success request with data
{
code: "000",
msg: "Successfully logged-in",
data: {
token: { accessToken: "..." },
user: { id: "1", name: "John" }
}
}
// Success request with validation
{
code: "001",
msg: "Validation error",
data: {
validation: {
name: "The name field is required",
email: "The email has been taken"
}
}
}Option 2:
// Success request with data
{
code: "000",
msg: "Successfully logged-in",
data: {
token: { accessToken: "..." },
user: { id: "1", name: "John" }
},
error: null
}
// Success request with validation
{
code: "001",
msg: "Validation error",
data: null,
error: {
validation: {
name: "The name field is required",
email: "The email has been taken"
}
}
}I'm working on an Express API, and I was curious what the current consensus is on JSON formats for API requests and responses? I've been using Google's JSON style guide, which I've enjoyed. Do you all have preferences? Are there pitfalls to watch out for?