Invalid JSON message received - rest

I'm trying to POST into an API I have made, and I am testing it using Postman. I am getting back a 400 Bad Request error back as a response with the message Invalid JSON message received.
This is an example of the record being feedback to the user using GET.
{
"id":3,
"title":"Radio Etiquette Book",
"summary":"This book provides advice on how to present a radio programme with flair.",
"timestamp":"2016-12-22T18:18:20+0000",
"author":{"id":1,...***},
"reviews":
}
I presume the problem is with author because author contains sub fields, such as ID, username, password and sub classes called entries (books created by that author), and reviews (reviews written by that author).
How can I POST a new entry to avoid a 400 Bad Request error? I'm not sure which value it is, that I am posting incorrectly, but debating on whether it is actually author, and how it should be entered.

You can use a site like JSONLint to inspect whether or not the JSON you're trying to send is properly formatted. It should be able to show you the line of the error and why it might not match the JSON spec.
link to JSONLint

Related

API design - Optional body in client request - Status code to return if validation fails

In our API, one of the endpoint will expect clients to provide body/payload only in certain scenario.
If the API is unable to generate a payload for given request based on the origin of the client then, we want our API to provide response with the right status code to the client, so that they know they have to provide additional information. Once the client fulfills the request with body/payload then the api will process the request as normal.
I just wanted to know is there any standard, predefined status code or procedure to implement this kind of endpoint in API design or do we have to just reject the request with some custom status code and then ask the client to implement a logic based on custom code?.
Thanks,
Vinoth
HTTP Status codes don't, nor are they intended to, map precisely against every real world error. They represent categories of error.
For example, a 404 means that the resource couldn't be found, but if your path is /customers/11/animals/5 then there are several things which could be wrong with the path. customer 11 may not have an animal 5 for example, or there may be no customer 11. There is no http response for "animal not found". Or your API may not have any calls with that pattern of URL to begin with.
You should return a status code which represents what "category" of error you have (in this case, something was not found), and the response body should contain more specific details about the error. To make things simpler, I find it helpful if the data structure is the same for a success and error (it makes parsing much easier) with a "data" field which varies per response.
Here is one example:
status code: 404 not found
body: {
"messageDetailCode" :"CustomerNotFound",
"messageDetail" : "Customer not found",
"data" : null
}
Further reading:
What's an appropriate HTTP status code to return by a REST API service for a validation failure?

download only the new content in email reply by google gmail api

I am trying to access Gmail messages via google API.
https://developers.google.com/gmail/api/v1/reference/users/threads
But the payload field returns the base64 of the body of the email. When an email is in a thread, it is usually to reply to a previous email. Therefore only the reply part is useful to show. The reply part can be shown by the GUI interface. Is there a way to get only the reply part via the API?
Unfortunately, there's no direct method of obtaining the last reply for each thread.
If you want to retrieve the last reply of the email threads you should first of all retrieve all the messages by using a GET request like this:
GET https://www.googleapis.com/gmail/v1/users/userId/messages
The request response will look something like this:
{
"messages": [
users.messages Resource
],
"nextPageToken": string,
"resultSizeEstimate": unsigned integer
}
Where the users.messages Resource looks something like this:
{
"id": "",
"threadId": ""
}
Having the list of all the users.messages Resources, the ones which contain the same threadId are the emails which in fact contain replies.
So in order to obtain the last reply, you could find which threadIds appear more than once, and then retrieve the last occurrence of it as it is the last reply. Or if you want all the replies (apart from the original email), you can retrieve all the occurrences apart from the first one (which is represented by the original email).
Lastly, to retrieve the message you can use a GET request like this:
GET https://www.googleapis.com/gmail/v1/users/userId/messages/id
Note: The userId is represented by the email address from which you want to retrieve the emails/replies and the id is represented by the id of the message.
Reference
Users.threads: list;
Users.threads: get;
Users.messages: list;
Users.messages: get.

Which HTTP code should be return from REST API?

im currently working on a website which has Spring at backend and Angularjs at front side and we had discussed about back end responses to handle frontend's message dialogs and i have a question to ask:
Lets say i have an API :
GET : /getstatistics
Request params : fromTime,toTime ( in timestamp format)
And if client make a request with invalid params like a string, which response code should be returned from server ? HTTP 400 bad request and response body with a message " fromTime and toTime should be in timestamp format" or HTTP 200 with same message?
I saw some Google's APIs for example Oauth, they're returning code 200 for a request with invalid access_token but ,in our project my opinion it should be HTTP 400 because Javascript has success and error callbacks, is it better for it just pop a red color dialog with message inside rather than a HTTP 200 code then still need to check the content of the message?
Any advides and opinions are appreciated.
Thanks!
You should be returning a 400 error for bad request. Check out this reference.
The server cannot or will not process the request due to something
that is perceived to be a client error (e.g., malformed request
syntax, invalid request message framing, or deceptive request
routing).
Please have a look at RFC7231#section-6
A client MUST understand the class of any status code, as indicated by
the first digit
and,
4xx (Client Error): The request contains bad syntax or cannot be
fulfilled
Bad syntax can be something like you've mentioned in your question (making a request with invalid parameters, like a string).
I keep these two references handy whenever I'm designing RESTful APIs, might be helpful for you too:
https://httpstatuses.com/
http://www.restapitutorial.com/httpstatuscodes.html
Yes you are right, the http code should be 400 in your case. Your discussion here normally should be whether you need to return 400 or 422. For this you can check the accepted response for this SO question 400 vs 422 response to POST of data
I think it has something to do with how the parameters are used. If you use the resource, then a 404 should return. If the data is simply not valid then we decide to set a 409 Status to the request. It can't full fill it at 100% because of missing/invalid parameter.
HTTP Status Code "409 Conflict" was for us a good try because it's
definition require to include enough information for the user to
recognize the source of the conflict.
Reference: w3.org/Protocols/
Edit:
In any case, the status code 200 is incorrect here because there is an error. In response, you can then return specific information like this:
{
"errors": [
{
"userMessage": "Sorry, the parameter xxx is not valid",
"internalMessage": "Invalid Time",
"code": 34,
"more info": "http://localhost/"
}
]
}

What status code should I response with when there is no data found in my database

I am wondering what status code would I response with in my else statement from the code below:
if (album) {
res.status(200).json({error: false, data: {channel_id: album.attributes.channel_id, id: album.id}});
} else {
res.status(200).json({error: false, data: {message: 'There is not album found with this name'}});
}
I don't want to leave both of them 200 as I want from front end to manage messaged thru status code, for ex if it returns 200 I would say "Created Successfully" while in else case I would display "No data found".
What is your suggestion?
"No data found" should be 404.
"Created Successfully" should be 201.
For the 201 you should also specify a Location header for where another request can access the new resource.
Refs:
201 http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2
404 http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5
UPDATE:
I thought I'd expand on this, because the comments below point to thought processes I've battled with myself.
GET /some/thing responding 404 Not Found may mean a database entity not found, but could also mean there is no such API end point. HTTP itself doesn't do much to help differentiate these cases. The URL represents a resource. It's not a thing in itself to be considered differently from the thing it represents.
Some APIs respond 400 when a request is made to a non-existant endpoint, but personally I don't like this as it seems to contradict the way web servers respond to normal resource requests. It could also confuse developers building client applications, as it suggests something is wrong in the HTTP transport rather than in their own code.
Suppose you decide to use 404 for missing database entities and 400 for what you consider bad requests. This may work for you, but as your application grows you'll uncover more and more scenarios that simple status codes just can't communicate on their own. And this is my point..
My suggestion is that all API responses carry meaningful data in the body. (JSON or XML, or whatever you're using). A request for an invalid url may look like:
HTTP/1.1 404 Not Found
{ "error": "no_endpoint", "errorText":"No such API end point" }
Although, I agree with above post, I would also consider HTTP status 200 for some cases.
For example, you have Post and Post_Comments entities. When you request comments for give Post Id, you can have either have 404 (an error which you then need to handle on your REST API consumer side) or 200 which means that everything is OK and an empty array is returned. In the HTTP status 200 case, you do not need to handle an error. As an example, see how FB treats HTTP codes https://apigee.com/about/blog/technology/restful-api-design-what-about-errors

Zabbix API behavior with no "id" specified -- no JSON in response

I am writing JSON-RPC code to talk to the Zabbix API.
I have noticed that if I omit the "id" from the request, I get back a response with zero-length content. If I specify any "id" value, the content is a JSON object as documented in the API documentation.
Can I assume that if I provide "id" that I will always get back JSON describing the error if an error occurs, but otherwise I will get back a zero-length content and a status of 200 to document the success? I always want to know about errors, but for successful operations (like deleting something) it often will suffice to know that it succeeded.
Is this a general rule? Is it documented anywhere? If so, please tell me where.
According to the JSON-RPC 2.0 documentation, "A Notification is a Request object without an "id" member." The documentation goes on to state: "Notifications are not confirmable by definition, since they do not have a Response object to be returned. As such, the Client would not be aware of any errors (like e.g. "Invalid params","Internal error")."
So, if you omit the "id" it will never return an error, because it is a notification. For use with Zabbix, you should probably just stick to using an id. That way you can get verification and error messages.