REST API Framework. Recommended behavior for inval

2019-02-03 06:05发布

I am implementing a REST API Framework, and I wonder what the recommendedbehavior is, when a client submits an invalid querystring parameter.

I will illustrate what I mean with a specific example: Say, I have an API handler on the /api/contacts/ endpoint, and the handler provides a querystring filter named id, which enables clients to select certain contacts with the provided IDs.

So, a GET or DELETE request could be /api/contacts/?id=2&id=4&id=lalalala.

Clearly, there is no such thing as a Contact with id=lalalala. In this case, what should the server behave like?

  • Ignore the invalid Contact with id=lalalala, and only filter the contacts on the valid ids, 2 and 4.

  • Respond with an error code that indicates this error. If yes, which error code should be provided?

Thanks in advance.

Edit: To clarify; The main focus of the framework I develop, is having a predictable behavior and hence response codes. For this reason, I want the clients consuming an API built on this framework, to expect the least possible surprises. So, the question basically is: Should the API return an error in this case(and if yes, which)? Or ignore invalid filter entries, and only filter on the correct querystring parameters?

2条回答
老娘就宠你
2楼-- · 2019-02-03 06:35

Following the letter of the law, the response should be a 404 Not found. However, nobody is going to get too upset with you if you prefer to return 400 - bad request.

I would definitely return a 4XX status code though. You want the client to know that they made an error.

查看更多
萌系小妹纸
3楼-- · 2019-02-03 06:57

Since this is a REST call, we are talking about resources. And whenever we have a wrong filter, we should return a proper error code.

In this case i would go for 400 - bad request as the resource was found and correctly mapped (/api/contacts), but there was a problem with the query string part. Therefore a 400 and not a 404.

Would return a 404 if someone requested /api/contacts-all or some non-existant resource.

EDIT based on comments below

Agree to your comment. Ideally a 400 is a problem with the request. Going by that, you could use a 422 Unprocessable Entity. Please look at the stackoverflow link below and it talks about the same thing.

I would guess that developers around the world would be more comfortable seeing a 400 than 422 for such logical errors due to the fact that bigger companies are using 400 and not 422.

References: Http status codes and 400 for logical error vs malformed request

查看更多
登录 后发表回答