我想知道如何在REST API中做出回应。
I wanted to know how I should respond in my REST API.
有效示例:
blah/api/v1/dosomething/123以上是有效请求,目前我的HTTP状态为200,带有JSON响应
The above is a valid request and currently I have a HTTP Status of 200 with a JSON response
{ "dosomething": { "status": "OK", "results": "123" } }现在我的问题是,如果传递的参数无效(我期待一个整数字符串),我是否会返回200响应的HTTP响应将错误状态传回JSON响应中,或者我应该传递类似HTTP 400响应(错误请求)的内容,并在JSON响应中列出请求的错误/问题?
Now my question is, if the parameter passed is not valid ( I'm expecting a string of whole numbers ), do I return a HTTP Response of 200 and pass the error status back in the JSON response or should I pass something like a HTTP 400 response ( Bad request ) and list the error / issue with the request in the JSON response?
错误示例:
blah/api/v1/dosomething/123aJSON回复:
{ "dosomething": { "status": "ERROR", "errors": [ "Value passed: |123a| must be a integer." ] } }我的问题是,我应该在请求中传递200或400 HTTP状态,其中传递的参数不是我期望的那样?或者当请求正在工作时,这应该总是200响应吗?
Again my question is should I pass a 200 or 400 HTTP status on the request where the parameter passed is not what I'm expecting? Or should this always be a 200 response as the request is working?
什么是最佳做法?
推荐答案使用404.总是.404。不这样做是为了误解了URI和资源的性质。如果 blah/api/v1/dosomething/ 确定了资源, 123a 只是它的一个参数,然后其他代码才有意义。但它没有: blah/api/v1/dosomething/123 标识资源。如果不存在此类资源,则返回 404 Not Found 。
Use 404. Always. 404. To do otherwise is to misunderstand the nature of a URI and a resource. If blah/api/v1/dosomething/ identified the resource, and 123a were merely a parameter to it, then other codes could make sense. But it doesn't: blah/api/v1/dosomething/123 identifies the resource. If no such resource exists, return 404 Not Found.
您可能拥有处理两种资源的一些实现细节 blah/api/v1/dosomething/123 和 blah/api/v1/dosometh ing / 123a ,但它不是资源。来自Roy Fielding的论文:
You might possess some implementation detail that handles both resources blah/api/v1/dosomething/123 and blah/api/v1/dosomething/123a, but it is not the resource. From Roy Fielding's dissertation:
资源不是存储对象。资源不是服务器用来处理存储对象的机制。 resource是一个概念映射 - 服务器接收标识符(标识映射)并将其应用于其当前映射实现(通常是特定于集合的深树遍历的组合)和/或哈希表)找到当前负责的处理程序实现,然后处理程序实现根据请求内容选择相应的操作+响应。所有这些特定于实现的问题都是隐藏在Web界面后面; 他们的性质不能由只通过Web界面访问的客户端承担。
"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."
更多推荐
了解REST响应和HTTP状态代码
发布评论