我想知道我应该如何在我的 REST API 中做出响应。
有效示例:
http://blah.com/api/v1/dosomething/123
以上是一个有效的请求,目前我有一个 200 的 HTTP 状态和一个 JSON 响应
{
"dosomething": {
"status": "OK",
"results": "123"
}
}
现在我的问题是,如果传递的参数无效(我期待一串整数),我是返回 200 的 HTTP 响应并将错误状态传回 JSON 响应还是应该传递一些东西像 HTTP 400 响应(错误请求)并在 JSON 响应中列出请求的错误/问题?
错误示例:
http://blah.com/api/v1/dosomething/123a
JSON 响应:
{
"dosomething": {
"status": "ERROR",
"errors": [
"Value passed: |123a| must be a integer."
]
}
}
同样,我的问题是我应该在请求中传递 200 或 400 HTTP 状态,而传递的参数不是我所期望的吗?或者这应该始终是 200 响应,因为请求正在运行?
什么是最佳实践?
最佳答案
始终使用 404。 404. 否则就是误解了 URI 和资源的性质。如果 http://blah.com/api/v1/dosomething/
标识了资源,而 123a
只是它的一个参数,那么其他代码就有意义了。但它没有:http://blah.com/api/v1/dosomething/123
标识资源。如果不存在这样的资源,则返回 404 Not Found
。
您可能拥有一些处理资源 http://blah.com/api/v1/dosomething/123
和 http://blah.com/api/v1/dosomething/123a
,但它不是资源。来自 Roy Fielding 的 dissertation :
"The resource is not the storage object. The resource is not a mechanism that the server uses to handle the storage object. The resource is a conceptual mapping -- the server receives the identifier (which identifies the mapping) and applies it to its current mapping implementation (usually a combination of collection-specific deep tree traversal and/or hash tables) to find the currently responsible handler implementation and the handler implementation then selects the appropriate action+response based on the request content. All of these implementation-specific issues are hidden behind the Web interface; their nature cannot be assumed by a client that only has access through the Web interface."
关于json - 了解 REST 响应和 HTTP 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10950918/