Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which HTTP code should be return from REST API?

Tags:

rest

http

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!

like image 570
meobeo173 Avatar asked Dec 19 '22 12:12

meobeo173


1 Answers

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:

  1. https://httpstatuses.com/
  2. http://www.restapitutorial.com/httpstatuscodes.html
like image 87
Divyanshu Maithani Avatar answered Jan 09 '23 13:01

Divyanshu Maithani