本文介绍了缺少父资源的 REST API 代码/消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关正确响应代码的一些指南 &请求构成另一资源一部分的资源时的消息.

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

例如,一个 GET 请求:

For example, a GET request on:

用户/{id}

如果用户不存在,将返回 404,并显示未找到用户资源的消息.

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:

用户/{id}/朋友

我目前正在返回与第一个示例中相同的代码/消息.我应该返回一条专门与朋友资源相关的消息吗?我个人认为让 API 客户端知道未找到父资源更有帮助,以防您有更大的 URI 链.

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.

推荐答案

在这个特定的例子中,如果重点是让客户端区分对不存在的用户的好友请求,以及对不存在的用户的好友请求只是没有朋友,我认为在第一种情况下返回 404 是最有意义的,而在第二种情况下返回 200 并带有空集.

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.

换句话说,none"对于朋友来说是一个有效值.不会出现用户存在但他们的(可能为空的)朋友列表不存在的情况,因此为父资源发出 404 永远不会有任何歧义.

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.

这篇关于缺少父资源的 REST API 代码/消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 04:42