Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should a RESTful API return 400 or 404 when passed an invalid id

Tags:

rest

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.

like image 215
Justin Avatar asked Aug 19 '14 08:08

Justin


People also ask

Should a REST API return 404?

Based on the code above, is it correct to return a NOT_FOUND status ( 404 ), or should I be returning 204 , or some other more appropriate code? If you would expect a resource to be there, because it is looked up using an ID, then a 404 is expected. Something goes wrong, the resource you need to be there is not found.

When should you return 404 not found?

If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD be used instead.

Should REST API return ID?

It doesn't matter if the resource returns an ID field. It is up to the client to keep a map of where it was obtained from. In a + b, the server would create a new resource.

How do I fix REST API 404?

You fix this by opening the listen step in your VSM file, and changing the base path in there, so you don't get a 404 error. You could change that to "/api/" so any api requests are dealt-with, or "/api/retrieveId/" so only retrieveId messages are dealt-with, or "/" so all requests are dealt-with.


2 Answers

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/[email protected] will return 404 because the url path is invalid.

like image 105
Manoj Avatar answered Sep 20 '22 08:09

Manoj


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.

like image 23
Rudy Avatar answered Sep 18 '22 08:09

Rudy