[英]Which HTTP code to use, in a REST API, for a subresource if the parent resource doesn't exist?
My team and I are coding a REST API, but some concepts are still not fully understood. 我和我的团队正在编写REST API,但仍然没有完全理解一些概念。
In a given resource: objective/{id}/goal
where goal is collection 在给定资源中: objective/{id}/goal
是目标是集合
If the consumer tries to reach an objective that doesn't exist, the API will return status code 404
, pretty simple. 如果消费者试图达到不存在的目标,API将返回状态代码404
,非常简单。
ex: objective/999
returns 404
例如: objective/999
返回404
For some reason the consumer tries to fetch the goals from this non existing resource: 出于某种原因,消费者试图从这个不存在的资源中获取目标:
ex: objective/999/goal
returns ?
例如: objective/999/goal
回归?
Which is the most suitable code to return? 哪个是最合适的返回代码? I have a feeling that this should be a 404
too. 我觉得这也应该是404
。 Some people are considering another error code, because the API should somehow inform that the parent resource doesn't exist in the first place. 有些人正在考虑另一个错误代码,因为API应该以某种方式告知父资源首先不存在。
Use 404. Keep in mind that a 404 response may contain a response body. 使用404.请记住,404响应可能包含响应正文。 So you could respond with something like the following: 所以你可以用以下内容回复:
Request
GET /objective/7/goal
Response
404 Not Found
{
"type": "ParentNotFound",
"description": "The parent resource was not found.",
"parent_uri": "/objective/7"
}
In general, it's a good idea to include some kind of response body for error status codes. 通常,为错误状态代码包含某种响应主体是个好主意。 Even when the error status code is being used in a standard way, it's still nice as the API client to see a human message about why I'm seeing the error. 即使以标准方式使用错误状态代码,作为API客户端仍然可以看到关于我看到错误的原因的人类消息。 The benefit is even greater when the error status code is being used in an almost standard yet slightly off way. 当错误状态代码以几乎标准但略微偏离的方式使用时,其好处甚至更大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.