Is there any standard for JSON API response format? - json

Do standards or best practices exist for structuring JSON responses from an API? Obviously, every application's data is different, so that much I'm not concerned with, but rather the "response boilerplate", if you will. An example of what I mean:
Successful request:
{
"success": true,
"payload": {
/* Application-specific data would go here. */
}
}
Failed request:
{
"success": false,
"payload": {
/* Application-specific data would go here. */
},
"error": {
"code": 123,
"message": "An error occurred!"
}
}

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.

I guess a defacto standard has not really emerged (and may never).
But regardless, here is my take:
Successful request:
{
"status": "success",
"data": {
/* Application-specific data would go here. */
},
"message": null /* Or optional success message */
}
Failed request:
{
"status": "error",
"data": null, /* or optional error payload */
"message": "Error xyz has occurred"
}
Advantage: Same top-level elements in both success and error cases
Disadvantage: No error code, but if you want, you can either change the status to be a (success or failure) code, -or- you can add another top-level item named "code".

Assuming you question is about REST webservices design and more precisely concerning success/error.
I think there are 3 different types of design.
Use only HTTP Status code to indicate if there was an error and try to limit yourself to the standard ones (usually it should suffice).
Pros: It is a standard independent of your api.
Cons: Less information on what really happened.
Use HTTP Status + json body (even if it is an error). Define a uniform structure for errors (ex: code, message, reason, type, etc) and use it for errors, if it is a success then just return the expected json response.
Pros: Still standard as you use the existing HTTP status codes and you return a json describing the error (you provide more information on what happened).
Cons: The output json will vary depending if it is a error or success.
Forget the http status (ex: always status 200), always use json and add at the root of the response a boolean responseValid and a error object (code,message,etc) that will be populated if it is an error otherwise the other fields (success) are populated.
Pros: The client deals only with the body of the response that is a json string and ignores the status(?).
Cons: The less standard.
It's up to you to choose :)
Depending on the API I would choose 2 or 3 (I prefer 2 for json rest apis).
Another thing I have experienced in designing REST Api is the importance of documentation for each resource (url): the parameters, the body, the response, the headers etc + examples.
I would also recommend you to use jersey (jax-rs implementation) + genson (java/json databinding library).
You only have to drop genson + jersey in your classpath and json is automatically supported.
EDIT:
Solution 2 is the hardest to implement but the advantage is that you can nicely handle exceptions and not only business errors, initial effort is more important but you win on the long term.
Solution 3 is the easy to implement on both, server side and client but it's not so nice as you will have to encapsulate the objects you want to return in a response object containing also the responseValid + error.

The RFC 7807: Problem Details for HTTP APIs is at the moment the closest thing we have to an official standard.

Following is the json format instagram is using
{
"meta": {
"error_type": "OAuthException",
"code": 400,
"error_message": "..."
}
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}

I will not be as arrogant to claim that this is a standard so I will use the "I prefer" form.
I prefer terse response (when requesting a list of /articles I want a JSON array of articles).
In my designs I use HTTP for status report, a 200 returns just the payload.
400 returns a message of what was wrong with request:
{"message" : "Missing parameter: 'param'"}
Return 404 if the model/controler/URI doesn't exist
If there was error with processing on my side, I return 501 with a message:
{"message" : "Could not connect to data store."}
From what I've seen quite a few REST-ish frameworks tend to be along these lines.
Rationale:
JSON is supposed to be a payload format, it's not a session protocol. The whole idea of verbose session-ish payloads comes from the XML/SOAP world and various misguided choices that created those bloated designs. After we realized all of it was a massive headache, the whole point of REST/JSON was to KISS it, and adhere to HTTP. I don't think that there is anything remotely standard in either JSend and especially not with the more verbose among them. XHR will react to HTTP response, if you use jQuery for your AJAX (like most do) you can use try/catch and done()/fail() callbacks to capture errors. I can't see how encapsulating status reports in JSON is any more useful than that.

For what it's worth I do this differently. A successful call just has the JSON objects. I don't need a higher level JSON object that contains a success field indicating true and a payload field that has the JSON object. I just return the appropriate JSON object with a 200 or whatever is appropriate in the 200 range for the HTTP status in the header.
However, if there is an error (something in the 400 family) I return a well-formed JSON error object. For example, if the client is POSTing a User with an email address and phone number and one of these is malformed (i.e. I cannot insert it into my underlying database) I will return something like this:
{
"description" : "Validation Failed"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Invalid phone number."
} ],
}
Important bits here are that the "field" property must match the JSON field exactly that could not be validated. This allows clients to know exactly what went wrong with their request. Also, "message" is in the locale of the request. If both the "emailAddress" and "phoneNumber" were invalid then the "errors" array would contain entries for both. A 409 (Conflict) JSON response body might look like this:
{
"description" : "Already Exists"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Phone number already exists for another user."
} ],
}
With the HTTP status code and this JSON the client has all they need to respond to errors in a deterministic way and it does not create a new error standard that tries to complete replace HTTP status codes. Note, these only happen for the range of 400 errors. For anything in the 200 range I can just return whatever is appropriate. For me it is often a HAL-like JSON object but that doesn't really matter here.
The one thing I thought about adding was a numeric error code either in the the "errors" array entries or the root of the JSON object itself. But so far we haven't needed it.

Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.
As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?
Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:
https://github.com/adnan-kamili/rest-api-response-format
Swagger file:
https://github.com/adnan-kamili/swagger-sample-template

The point of JSON is that it is completely dynamic and flexible. Bend it to whatever whim you would like, because it's just a set of serialized JavaScript objects and arrays, rooted in a single node.
What the type of the rootnode is is up to you, what it contains is up to you, whether you send metadata along with the response is up to you, whether you set the mime-type to application/json or leave it as text/plain is up to you (as long as you know how to handle the edge cases).
Build a lightweight schema that you like.
Personally, I've found that analytics-tracking and mp3/ogg serving and image-gallery serving and text-messaging and network-packets for online gaming, and blog-posts and blog-comments all have very different requirements in terms of what is sent and what is received and how they should be consumed.
So the last thing I'd want, when doing all of that, is to try to make each one conform to the same boilerplate standard, which is based on XML2.0 or somesuch.
That said, there's a lot to be said for using schemas which make sense to you and are well thought out.
Just read some API responses, note what you like, criticize what you don't, write those criticisms down and understand why they rub you the wrong way, and then think about how to apply what you learned to what you need.

JSON-RPC 2.0 defines a standard request and response format, and is a breath of fresh air after working with REST APIs.

The basic framework suggested looks fine, but the error object as defined is too limited. One often cannot use a single value to express the problem, and instead a chain of problems and causes is needed.
I did a little research and found that the most common format for returning error (exceptions) is a structure of this form:
{
"success": false,
"error": {
"code": "400",
"message": "main error message here",
"target": "approx what the error came from",
"details": [
{
"code": "23-098a",
"message": "Disk drive has frozen up again. It needs to be replaced",
"target": "not sure what the target is"
}
],
"innererror": {
"trace": [ ... ],
"context": [ ... ]
}
}
}
This is the format proposed by the OASIS data standard OASIS OData and seems to be the most standard option out there, however there does not seem to be high adoption rates of any standard at this point. This format is consistent with the JSON-RPC specification.
You can find the complete open source library that implements this at: Mendocino JSON Utilities. This library supports the JSON Objects as well as the exceptions.
The details are discussed in my blog post on Error Handling in JSON REST API

For those coming later, in addition to the accepted answer that includes HAL, JSend, and JSON API, I would add a few other specifications worth looking into:
JSON-LD, which is a W3C Recommendation and specifies how to build interoperable Web Services in JSON
Ion Hypermedia Type for REST, which claims itself as a "a simple and intuitive JSON-based hypermedia type for REST"

There is no lawbreaking or outlaw standard other than common sense. If we abstract this like two people talking, the standard is the best way they can accurately understand each other in minimum words in minimum time. In our case, 'minimum words' is optimizing bandwidth for transport efficiency and 'accurately understand' is the structure for parser efficiency; which ultimately ends up with the less the data, and the common the structure; so that it can go through a pin hole and can be parsed through a common scope (at least initially).
Almost in every cases suggested, I see separate responses for 'Success' and 'Error' scenario, which is kind of ambiguity to me. If responses are different in these two cases, then why do we really need to put a 'Success' flag there? Is it not obvious that the absence of 'Error' is a 'Success'? Is it possible to have a response where 'Success' is TRUE with an 'Error' set? Or the way, 'Success' is FALSE with no 'Error' set? Just one flag is not enough? I would prefer to have the 'Error' flag only, because I believe there will be less 'Error' than 'Success'.
Also, should we really make the 'Error' a flag? What about if I want to respond with multiple validation errors? So, I find it more efficient to have an 'Error' node with each error as child to that node; where an empty (counts to zero) 'Error' node would denote a 'Success'.

I used to follow this standard, was pretty good, easy, and clean on the client layer.
Normally, the HTTP status 200, so that's a standard check which I use at the top. and I normally use the following JSON
I also use a template for the API's
dynamic response;
try {
// query and what not.
response.payload = new {
data = new {
pagination = new Pagination(),
customer = new Customer(),
notifications = 5
}
}
// again something here if we get here success has to be true
// I follow an exit first strategy, instead of building a pyramid
// of doom.
response.success = true;
}
catch(Exception exception){
response.success = false;
response.message = exception.GetStackTrace();
_logger.Fatal(exception, this.GetFacadeName())
}
return response;
{
"success": boolean,
"message": "some message",
"payload": {
"data" : []
"message": ""
... // put whatever you want to here.
}
}
on the client layer I would use the following:
if(response.code != 200) {
// woops something went wrong.
return;
}
if(!response.success){
console.debug ( response.message );
return;
}
// if we are here then success has to be true.
if(response.payload) {
....
}
notice how I break early avoiding the pyramid of doom.

I use this structure for REST APIs:
{
"success": false,
"response": {
"data": [],
"pagination": {}
},
"errors": [
{
"code": 500,
"message": "server 500 Error"
}
]
}

A bit late but here is my take on HTTP error responses, I send the code, (via status), the generic message, and details (if I want to provide details for a specific endpoint, some are self explanatory so no need for details but it can be custom message or even a full stack trace depending on use case). For success it's a similar format, code, message and any data in the data property.
ExpressJS response examples:
// Error
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: `missing ${missingParam}`,
}
});
// or
res
.status(422)
.json({
error: {
message: 'missing parameters',
details: 'expected: {prop1, prop2, prop3',
}
});
// Success
res
.status(200)
.json({
message: 'password updated',
data: {member: { username }}, // [] ...
});

Best Response for web apis that can easily understand by mobile developers.
This is for "Success" Response
{
"code":"1",
"msg":"Successfull Transaction",
"value":"",
"data":{
"EmployeeName":"Admin",
"EmployeeID":1
}
}
This is for "Error" Response
{
"code": "4",
"msg": "Invalid Username and Password",
"value": "",
"data": {}
}

Related

freeradius 3.0.17 rlm_rest parsing json response

I'm trying to authenticate RADIUS Requests against a RESTful API (provided by Customer) using rlm_rest.
The problem I am facing is that
response JSON format (of REST API provided by Customer), is different from rlm_rest default format (indicated in etc/raddb/mods-enabled/rest).
My Virtual Server configuration as below:
Default
authorize {
...
...
rest
if (ok) {
update control {
Auth-Type := rest
}
}
}
mods-enabled/rest
authorize {
uri = "https://3rd-party-API/auth"
method = 'post'
body = 'json'
chunk = 0
tls = ${..tls}
data = '{
"code": 1,
"identifier": %I,
"avps": {
"User-Name": ["%{User-Name}"],
"NAS-IP-Address": ["%{NAS-IP-Address}"],
"Called-Station-Id": ["%{Called-Station-Id}"],
"Calling-Station-Id": ["%{Calling-Station-Id}"],
"NAS-Identifier": ["%{NAS-Identifier}"]
}
}'
}
Result
/sbin/radiusd -Xxx
HTTP response code
200
JSON Body
{
"code": "2",
"identifier": "91",
"avps": {
"Customer-Attributes": "Hello"
...
...
"Acct-Interim-Interval": "300"
}
}
The JSON structure is different from the example, and xlat parse
"code"
"identifier"
"avps"
And, of course, xlat finds no attributes match with the dictionary, while it cannot find "avps" and won't dig deeper.
So I was wondering is there anyway to either
Define the response JSON structure for xlat to parsing
Insert a "is_json" or "do_xlat" flag into the JSON ("avps"), and hope xlat will then dig deeper
Save the JSON and parse with exec/rlm_exec (using JQ or any other bash/JSON tools)
Please advise if there is any workaround. Thanks!
In FreeRADIUS version 4, there's a rlm_json module, which implements a custom node query language based on xpath (jpath), it is extremely limited and only supports some very basic queries (feel free to enhance it via PR :) ).
Below is an example I pulled out of my library of customer configurations. You can see here it's pulling out two keys (externalID and macAddress) from the root level of the JSON doc and assigning them to a couple of custom attributes (Subscriber-ID and Provisioned-MAC).
map json "%{rest_api:https://${modules.rest[rest_api].server}/admin/api/${modules.rest[rest_api].api_key}/external/getDeviceBySerialNumber?certificateSerialNumber=%{lpad:&TLS-Client-Cert-Serial 40 0}}" {
&Subscriber-ID := '$.externalId'
&Provisioned-MAC := '$.macAddress'
}
The xlat expansion can also be modified to send HTTP body data. Just put a space after the URL and pass your custom JSON blob.

Is there an alternative to "type": "undefined" in JSON?

I'm working with Amazon API Gateway. I am creating a model for an REST API. The model gets hung up on:
"tiers": {
"type": "array",
"items": {
"type": "undefined"
}
}
The API data model uses JSON schema draft 4.
The error returned is:
Invalid model specified: Validation Result: warnings : [], errors :
[Invalid model schema specified]
Anyone run into this before?
Things I've tried:
Removing this property = script creates model
Changing "Undefined" to "null" = script creates model
The "null" seems like the right option but, I've not been able to back it up. Some guidance and/or clarification would be greatly appreciated.
Thanks,
Todd
You don't seem to be actually defining a schema for your data, refer to the API gateway docs to re-define your model.
undefined is not a valid json value, even though it is valid in javascript. From the official json standard (ECMA-404, Section 5):
A JSON value can be an object, array, number, string, true, false, or
null.
For json, use null instead of undefined: { "something": null }
Using null instead of undefined is definitely not ideal, but it's a standard you can count on when consuming third-party services.

Response custom error when key not satisfies the exact value in couchbase view

I have a document like -
{
"fullUserName": "xxyz",
"userFirstName": "xx",
"userLastName": "xx",
"primaryRole": "xy",
"actualRole": "rrr",
"userId": "abcd1234",
"password":"c28f5c7cb675d41c7763ab0c42d",
"type":"login",
"channels":"*"
}
and view -
function (doc, meta) {
if(doc.userId,doc.password,doc.type){
emit([doc.userId,doc.password,doc.type],doc);
}
}
When the key matches with the docment's property it return the document otherwise it return empty JSON like -
{"total_rows":2,"rows":[
]
}
Now I want to response the error message in JSON format when the key does not match for example-
{
"Error-Code":"400",
"Error-Msg":"user id and password does not match"
}
Is there any way to do so,Please correct if I am moving in the wrong direction.
Thanks in advance.
You shouldn't directly expose the view query result to your users but interpret it instead.
So make a view request, look at the response and do the business logic of checking there. For example:
"if result is empty it can only be because the user is unknown or the password hash didn't match the user, so return a business-specific error message, otherwise carry on with login"
There's no way you can change the behavior and response format of the server, and that doesn't make much sense to do so anyway. This is the API and contract of how you interact with the server. You should add your own business logic in a layer in between.

REST API error codes return structure

I am writing a REST API and I have stumbled upon a problem. What is the best way to return the validation errors.
Until now I have been returning the error messages dumped into a general error code (let's say bad request for example)
{
"status": 400,
"error": {
"code": 1, // General bad request code
"message": [
"The Key \"a\" is missing",
"The Key \"b\" is missing",
"The Key \"c\" is missing",
"Incorrect Format for field \"y\""
]
}
)
I have researched a little more about how should a good API response should look like and I thought of the following options:
Stop at the first encountered error and return a response with the specific error code
{
"status": 400, //Same as the HTTP header returned
"error" {
"code": 1, // Specific field validation error code
"message": "Field \"x\" is missing from the array structure",
"developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}",
"more_info" => "www.api.com/help/errors/1"
}
)
Parse all the request data and return multiple field validation errors.
{
"status": 400,
"error": {
"code": 1 //General bad Request code
"message": "Bad Request",
"developer_message": "Field validation errors."
"more_info": "www.api.com/help/errors/1",
"error_details": {
0: {
"code": 2 // Specific field validation error code
"message": "Field \"x\" is missing from the array structure",
"developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}",
"more_info": "www.api.com/help/errors/2"
},
1: {
"code": 3 // Specific field validation error code
"message": "Incorrect Format for field \"y\"",
"developer_message": "The field \"y\" must be in the form of \"Y-m-d\"",
"more_info": "www.api.com/help/errors/3"
}
}
}
}
In my opinion option 2 would be the right way (it gives more useful information to the developers/end users and the server load might be lower(less requests/no need to revalidate valid data/no need to compute the signature and authenticate the user)), but I am wandering what are the best practices, and if there is another way to treat this kind of problems.
Also i think option 1 is still valid if i get a single fatal error in the flow of the script.(not validation errors)
Please note that the code is just a simple array just so it is easier to follow. The response format will be JSON or XML.
Let's look to Facebook's Graph API. That is hit hard, and a great many errors are most likely generated. Here is what Facebook returns on an API error:
{
"error": {
"message": "Message describing the error",
"type": "OAuthException",
"code": 190,
"error_subcode": 460,
"error_user_title": "A title",
"error_user_msg": "A message"
}
}
They try to make the Graph API as useful as possible, but they seem return a specific error with a code and a subcode (Ref). The fact that each error has its own code means it's easier to search for said code or message as a starting point for debugging. That's probably why they don't accumulate error messages in their official error response. If it's good enough and convenient for Facebook, it's probably good enough for us.
Sample error responses:
{
"error": {
"message": "(#200) Must have a valid access_token to access this endpoint",
"type": "OAuthException",
"code": 200
}
}
and
"error": {
"message": "(#604) Your statement is not indexable. The WHERE clause must contain
an indexable column. Such columns are marked with * in the tables linked from
http://developers.facebook.com/docs/reference/fql ",
"type": "OAuthException",
"code": 604
}
Then there is JSend which "is a specification that lays down some rules for how JSON responses from web servers should be formatted." Their goal is:
There are lots of web services out there providing JSON data, and each has its own way of formatting responses. Also, developers writing for JavaScript front-ends continually re-invent the wheel on communicating data from their servers. While there are many common patterns for structuring this data, there is no consistency in things like naming or types of responses. Also, this helps promote happiness and unity between backend developers and frontend designers, as everyone can come to expect a common approach to interacting with one another.
Here is a sample error message:
{
"status" : "fail",
"data" : { "title" : "A title is required" }
}
It looks like Facebook and this group trying to set like an industry standard are opting for your choice #1.
Bounty Question
In response to the bounty request of "if anyone went #2 and maybe has any improvements on it?", there is a design pattern from Pragmatic RESTful API that states:
Validation errors will need a field breakdown. This is best modeled by using a fixed top-level error code for validation failures and providing the detailed errors in an additional errors field, like so:
{
"code" : 1024,
"message" : "Validation Failed",
"errors" : [
{
"code" : 5432,
"field" : "first_name",
"message" : "First name cannot have fancy characters"
},
{
"code" : 5622,
"field" : "password",
"message" : "Password cannot be blank"
}
]
}
I have used #2 myself a couple times. Is it better than #1? I think that depends on what your API is being used for.
I like #2 because it gives a developer who is testing the API with some test calls a quick overview of all the errors/mistakes he made in a request, so he knows immediately which errors/mistakes he has to fix to make that request valid. If you return the errors one by one (like in #1) you have to keep retrying the request and cross fingers hoping it will be valid this time.
But as I said #2 is very useful for developers, but the reasons don't really apply to end users. End users don't usually care how it's implemented. Whether the software is doing 1 request which returns 5 errors or 5 subsequent requests which return 1 error each.
As long as it's handled well in the client, the end user shouldn't notice the difference. How to handle that of course very much depends on what the client actually is.
Next to speeding up the development, another benefit of #2 (in production) is that it requires less requests to be made, which of course decreases the server load.
I would like to know if anyone went #2 and maybe have any improvements on it so I opened a bounty.
Sure there are improvements to be made. As it is, there is some data in the body that can be omitted.
{
"status": 400,
"error": {
"code": 1 //General bad Request code
"message": "Bad Request",
"developer_message": "Field validation errors."
"more_info": "www.api.com/help/errors/1",
"error_details": {
0: {
"code": 2 // Specific field validation error code
"message": "Field \"x\" is missing from the array structure",
"developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}",
"more_info": "www.api.com/help/errors/2"
},
1: {
(
"code": 3 // Specific field validation error code
"message": "Incorrect Format for field \"y\"",
"developer_message": "The field \"y\" must be in the form of \"Y-m-d\"",
"more_info": "www.api.com/help/errors/3"
)
}
)
With HTTP responses, the status code should not go in the body, but in the header. This means that "status": 400 and "message": "Bad Request" can be omitted here. 400 should be the response's status code, and 400 means Bad Request. It's a HTTP standard and doesn't have to be explained in the response. Also "developer_message": "Field validation errors." is kind of a duplicate, since the specific errors are already included in each seperate error, so we could leave that out.
That leaves
{
"error": {
"code": 1 //General bad Request code
"more_info": "www.api.com/help/errors/1",
"error_details": {
0: {
"code": 2 // Specific field validation error code
"message": "Field \"x\" is missing from the array structure",
"developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}",
"more_info": "www.api.com/help/errors/2"
},
1: {
(
"code": 3 // Specific field validation error code
"message": "Incorrect Format for field \"y\"",
"developer_message": "The field \"y\" must be in the form of \"Y-m-d\"",
"more_info": "www.api.com/help/errors/3"
)
}
)
"code": 1 //General bad Request code
"more_info": "www.api.com/help/errors/1",
These 2 lines don't really make sense anymore now. They are also not required, since each error has it's own code and info link, so we might strip these lines as well, leaving this
{
"error": {
"error_details": {
0: {
"code": 2 // Specific field validation error code
"message": "Field \"x\" is missing from the array structure",
"developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}",
"more_info": "www.api.com/help/errors/2"
},
1: {
(
"code": 3 // Specific field validation error code
"message": "Incorrect Format for field \"y\"",
"developer_message": "The field \"y\" must be in the form of \"Y-m-d\"",
"more_info": "www.api.com/help/errors/3"
)
}
)
The 400 status code already indicates there was an error, so you don't have to indicate "error": {error details} anymore, because we already know there was an error. The list of errors can simply become the root object:
[
{
"code": 2//Specificfieldvalidationerrorcode
"message": "Field \"x\" is missing from the array structure",
"developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}",
"more_info": "www.api.com/help/errors/2"
},
{
"code": 3//Specificfieldvalidationerrorcode
"message": "Incorrect Format for field \"y\"",
"developer_message": "The field \"y\" must be in the form of \"Y-m-d\"",
"more_info": "www.api.com/help/errors/3"
}
]
So all that's left in the body now is simply a list of errors.
The status code is specified in the response header.
The details are specified in the response body.
I recently worked against a Rest API that would return multiple warnings or errors in the results. Starting from your Sample #2, I would modify it as follows:
{
"status": 400,
"results" : null,
"warnings": {
0: {
// Build a warning message here, sample text to show concept
"code": 1 // Specific field validation error code
"message": "It is no longer neccessary to put .js on the URL"
}
}
"errors": {
0: {
"code": 2 // Specific field validation error code
"message": "Field \"x\" is missing from the array structure"
"developer_message": "The request structure must contain the following fields {a,b,c{x,y,z}}",
},
1: {
"code": 3 // Specific field validation error code
"message": "Incorrect Format for field \"y\"",
"developer_message": "The field \"y\" must be in the form of \"Y-m-d\""
}
}
}
This would provide you the ability to provide results, with multiple warnings or errors as needed in your response.
And yes, this does have some bloat in the structure, but it also provides an easy interface for a developer to always get their data back in the same structure.
I would also remove the following items as IMHO they should be in the API docs (how to find help using an error code) instead of on every error:
"more_info": "www.api.com/help/errors/2"
"more_info": "www.api.com/help/errors/3"
Along those same lines, I'm not sure if you need both the message and developer_message. They appear to be redundant and as if you are trying to provide user error messages from the API when the caller failed to provide data correctly.
First of all you would have provided documentation for the Rest API methods for the customers. So it is expected from the customer/developer to provide valid data for the parameters.
Now having said that #1 is the best way to do Rest API. A developer's responsibility is to reduce server usage to the maximum possible extent. So if you encounter any fatal error, Construct a response with the corresponding error code and error message and return it.
Moreover we cannot be sure that there are more errors after the one we encountered. So there is no point in parsing the rest of the data. It will not work well considering the worst case.
Personally I would give the users less detail and either dump errors needed to the developers in a database log table or system logs. Due to the fact you are using JSON and that is most common on Apache servers and your code looks likely to be php (but your code example with curly braces could be a number of languages originating from PASCAL eg. C, C# PERL, PHP, CSharp). Here is how to put output custom errors to the system logs if you do not already know how in php http://php.net/manual/en/function.syslog.php . If your are using a rarer configuration IIS with JSON and CSharp there are .NET libraries to do similar too. If you give your users too much information when an error occurs you are also giving a hacker in the future a way of probing your website.
API's are not for humans. Therefore you don't need to return detailed error texts. You can even return an error code which means "missing parameter". Just don't forget to document it well.

Ember Data and mapping JSON objects

I have truly searched and I have not found a decent example of using the serializer to get objects from a differently formatted JSON response. My reason for not changing the format of the JSON response is outlined here http://flask.pocoo.org/docs/security/#json-security.
I'm not very good with javascript yet so I had a hard time understanding the hooks in the serialize_json.js or maybe I should be using mapping (I just don't know). So here is an example of my JSON response for many objects:
{
"total_pages": 1,
"objects": [
{
"is_completed": true,
"id": 1,
"title": "I need to eat"
},
{
"is_completed": false,
"id": 2,
"title": "Hey does this work"
},
{
"is_completed": false,
"id": 3,
"title": "Go to sleep"
},
],
"num_results": 3,
"page": 1
}
When ember-data tries to use this I get the following error:
DEBUG: -------------------------------
DEBUG: Ember.VERSION : 1.0.0-rc.1
DEBUG: Handlebars.VERSION : 1.0.0-rc.3
DEBUG: jQuery.VERSION : 1.9.1
DEBUG: -------------------------------
Uncaught Error: assertion failed: Your server returned a hash with the key total_pages but you have no mapping for it
Which totally makes when you look at my code for the data store:
Todos.Store = DS.Store.extend({
revision: 12,
adapter: DS.RESTAdapter.create({
mappings: {objects: "Todos.Todo"},
namespace: 'api'
})
});
My question is how do I deal with total_pages, num_results and page? And by deal, I mean ignore so I can just map the objects array.
All root properties you return in your JSON result are mapped to a DS.Model in Ember Data. You should not return properties that are not modelled or you should model them.
If you want to get rid of the error you should make an empty model for the properties you don't use.
Read more here
Why are you returning properties you don't want to use? Or is it out of your control?
The way to accomplish this is with a custom serializer. If all your data is returned from the server in this format you could simply create ApplicationSerializer like this:
DS.RESTSerilizer.extend({
normalizePayload: function(type, payload) {
delete payload.total_pages;
delete payload.num_results;
delete payload.page;
return payload;
}
});
That should allow Ember Data to consume your API seamlessly.
Ember is fairly opinionated about how things are done. Ember data is no exception. The Ember team works towards certain standards that it thinks is best, which is, in my opinion, a good thing.
Check out this post on where ember is going. TL;DR because there are so many varying implementations of api calls, they're setting their efforts towards supporting the JSON API.
From my understanding, there is no easy way to do what you're asking. Your best bet is to write your own custom adapter and serialized. This shouldn't be too hard to do, and has been done before. I recommend you having a look at the Tastypie adapter used for Python's Django Tastypie