REST API code/message for missing parent resource

陌路散爱 提交于 2019-12-23 07:36:39

问题


I'm looking for some guidance for the correct response code & message when requesting for a resource that forms part of another resource.

For example, a GET request on:

users/{id}

where the user does not exist would return a 404, with a message of user resource not found.

My question is, what should the following return when no user resource is found:

users/{id}/friends

I'm currently returning the same code/message as in the first example. Should I be returning a message relating specifically to the friends resource? I personally think it's more helpful to make the API client aware that the parent resource isn't found, incase you have a larger URI chain.


回答1:


In this particular example, if the point is to let the client differentiate between a friends request for a non-existent user, and a friends request for a user who simply has no friends, I think it would make the most sense to return 404 in the first case, and 200 with an empty set in the second.

In other words, "none" is a valid value for friends. There's no case where a user exists but their (potentially empty) list of friends doesn't, so there's never any ambiguity in issuing a 404 for the parent resource.




回答2:


I’d be tempted to return a 400 Bad Request header, and place the error message in the body of the response. Unfortunately there’s no right or wrong answer in this scenario, so go with what works best for you and your application.



来源:https://stackoverflow.com/questions/15384260/rest-api-code-message-for-missing-parent-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!