Why multiple status codes are required in RAML response? - rest

While defining RAML, in response body we will define response based on status codes like 200, 400, etc.
Why that seperate defination is required?
sample RAML
responses:
200:
body:
type: User
400:
body:
type: ErrorMessage
From controller i can send like
response = Request.CreateResponse(HttpStatusCode.Ambiguous, error);
This will create response as 300 status.
While hitting the api from Postman, i can able to get the response with status 300.
So Is it really needed to define the response for different status codes?

Is it really needed to define the response for different status codes?
RAML is a way of generating documentation and clients. Sure, you could document you're going to return a body of X and actually return a body of Y, but all that will cause is annoyed consumers.
So you could return the same response type for all response codes, or document when the response type varies per response code.

I think you are misunderstanding what RAML is.
RAML is documenting your API, it does not implement your API. So yes, you can have an implementation that is different from what your RAML specifies.
Is it really needed to define the response for different status codes?
No, in RAML the whole responses is optional. So you could just leave it out.
But the idea is that you specify RAML as close as your implementation as you can, so it is useful for you and other people.
While defining RAML, in response body we will define response based on
status codes like 200, 400, etc. Why that seperate defination is
required?
Different status codes usually mean different response data.
For example if you are getting a dog by id (/dogs/1) then if the dog is found you will return status code 200 and the body will contain data about the dog. e.g. { name: "foo", colour: "brown", ...}
On the other hand if there's no dog with id 1, then you will return status code 404 and in the body something like: { message: "a dog with id 1 was not found" }

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?

Which http status code for 'entity not found'?

/persons?age=18
Imagine a search does not return any results (means: no entity found for the request).
If I'd return a 404 here, that would suggest that maybe the /persons path is invalid entirely.
Is there any accepted status code that could be return if the request was valid in general (means: the path exists, and the request parameters have been valid), but still there is no data to return?
204 is not suitable either, as this is used to tell the user "your request was 200 OK, but there will never be a response body to your request" (like for modifications).
Is there any accepted status code that could be return if the request was valid in general (means: the path exists, and the request parameters have been valid), but still there is no data to return?
200 is appropriate when the resource has a representation, even if that representation is an empty list.
# Request:
GET /persons?age=18
# Response:
200 OK
[]
Think "web search page that returns no results", downloading an empty file.
Jim Webber's 2011 talk may help with perspective here: the status codes and headers belong to the "transferring documents over a network" domain, not to your domain application protocol. The components that are specific to your application should be paying attention to the messages in the body of the response; the meta data is directed at general purpose components that are transferring documents.
Actually you should return 200.
The number of entities found does not change the http code.

Should HTTP Header Status match Body Status for RESTful calls

Building a RESTful web service endpoint and wondering what the best practice is for HTTP header status versus the status found in the body of the response. Should they always match, or can they be different? For example, in the event of a bad request, it's really our application layer that does the parsing and processing of the payload. So in the event the request made it to the application layer, should the HTTP header show a 200 (indicating no problems with the transport) while the response body contains a 400 (indicating a bad request)? Or should they always match? Both 400 at the header and in the body?
Thanks.
Generally speaking, it is a good practice to be consistent. Thus, if you intend to return the HTTP status code in your JSON body, it should be the same as the HTTP status code.
If you want to add more details regarding your application errors. The JSON-API standard defines some fields for JSON error bodies, such as:
code: an application-specific error code, expressed as a string value. For example, you could have different codes for HTTP 400 status code.
title: a short, human-readable summary of the problem that SHOULD NOT change from occurrence to occurrence of the problem, except for purposes of localization.
detail: a human-readable explanation specific to this occurrence of the problem. Like title, this field’s value can be localized.
Imagine that your application has the following route to get the details of a song (identified by :id parameter) that belongs to an artist (identified by :artist_id parameter):
GET /artists/:artist_id/songs/:id
This request may produce two different Not Found errors:
when the artist is not found
when the song is not found
For both situations you will return a HTTP 404 status code. However, in your json body you can add more details:
when the artist is not found
code: 10
title: Artist Not Found
detail: The artist with id #{artist_id} does not exist
when the song is not found
code: 12
title: Song Not Found
detail: The song with id #{id} does not exist for #{artist.name}
I also recommend you take a look on how JSON-API standard defines HTTP error code

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