Which HTTP code should be returned from the REST API?

微信扫一扫,分享到朋友圈

Which HTTP code should be returned from the 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:

微信扫一扫,分享到朋友圈

Which HTTP code should be returned from the REST API?

腾讯变阵解读:强化2B、对标今日头条、搭建大中台

上一篇

Stop the long-term task safely

下一篇

你也可能喜欢

Which HTTP code should be returned from the REST API?

长按储存图像,分享给朋友