Should a RESTful API return 400 or 404 when passed

2019-03-09 07:34发布

When building a RESTful API and a user provides an id of resource that does not exist, should you return 404 Not Found or 400 Bad Request.

For example:

https://api.domain.com/v1/resource/foobar

Where foobar does not exist.

标签: api rest
6条回答
\"骚年 ilove
2楼-- · 2019-03-09 07:40

Should be 404 ( Not Found ). 400 is used if you can't fulfill the request due to bad syntax, however for your case, the syntax is correct, however there is no resource foobar.

You can use 400 if user uses non-existent API like below :

https://api.domain.com/v1/nonexistAPI/xyz/xyz

You can also refer to this REST API Design Blog which tell you how to design your REST error codes.

查看更多
霸刀☆藐视天下
3楼-- · 2019-03-09 07:50

Is it a valid request? Can the id of the resource exist? Is it formatted as a proper id? Is it syntactically correct? etc.. If so then you can use, 404 Not Found. Otherwise 400 Bad Request is more suitable.

查看更多
Root(大扎)
4楼-- · 2019-03-09 07:55

404 Not Found is the proper answer I think, 400 is more about the body of the requests and not the resource identifier, so for example you can send that by validation errors.

查看更多
唯我独甜
5楼-- · 2019-03-09 07:55

According to the RFC (https://tools.ietf.org/html/rfc2616#section-10.4) the API should return 404 when "The server has not found anything matching the Request-URI", which is your example.

400 would be when the resource is found, but the request itself is malformed.

For instance: i. https://api.domain.com/v1/resource/foobar

where foobar DOES NOT exist should return 404

ii. https://api.domain.com/v1/resource/foobar where foobar DOES exist, but the request is wrong ({age:"NOTANINTEGER"}, a string instead of an int for example), it should return 400.

Hope I could help.

查看更多
戒情不戒烟
6楼-- · 2019-03-09 08:00

404 would be a more common practice one. Its for Resource Not Found. In your case the particular URL is not found.

400 is generally used for Bad Request. You can use this one for any bad request. For eg. MissingRequiredQueryParameter, InvalidInput.

查看更多
来,给爷笑一个
7楼-- · 2019-03-09 08:04

I would return 404 in case of resource does not exist(means the url path is wrong) and i will return 400 only if the rest call is made with some invalid data (@PathParam) for example
https://api.domain.com/v1/profile/test@email : here i am trying to get profile of email id, but the email itself is wrong, so I will return 400.
https://api.domain.com/v1/profile1111/test@email.com will return 404 because the url path is invalid.

查看更多
登录 后发表回答