休息服务返回404 [英] Rest service returns 404

查看:95
本文介绍了休息服务返回404的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果对rest服务的调用执行了数据库查询,但未找到结果并返回,则返回代码的最佳实践是什么.

What is the best practice in return codes if a call to a rest service executes a database query, no results are found and it returns.

应该是404还是200,并显示一条没有记录的消息?

URL正确解析并且仅返回了没有记录就没有发生服务器错误.

The URL has resolved correctly and no server error has occurred just that there are no records returned.

网址示例为:

http://localhost/app/pr_xyz/1234

用于检索属于现有用户1234的xyz列表.用户ID 1234已被检索到,并且已知存在于数据库中.此URL(pr_xyz)仅用于检索属于该用户的xyz列表.

Used to retrieve a list of xyz that belong to the existing user 1234. The user id 1234 has already been retrieved and is known to exist in the database. This URL (pr_xyz) is just to retrieve a list of xyz that belong to that user.

关系是1个用户到0个或多个xyz.

The relationship is 1 user to 0 or many xyz.

在这种情况下,现有用户没有xyz.这应该是带有有意义消息的404还是200.

In this case the existing user has no xyz. Should this be a 404 or 200 with meaningful message.

我也无法控制URL.

推荐答案

同意@Satya,它应该是200,但是我们可以通过反向工作来得出答案.

Agree with @Satya, it should be a 200, but we can arrive at the answer by working backwards.

因此,我们从 HTTP状态代码的完整列表开始..从底部开始.

So, we start with the full list of HTTP status codes.. Start from the bottom.

  • 这是服务器错误吗?不?那不是5xx
  • 这是客户端错误吗?可能是?也许不是4xx
  • 这显然不是重定向,所以它不是3xx.
  • 呼叫成功吗?也许.
  • 您是否要返回临时回复?不,它也不是1xx.

因此,通过消除过程,它们正在查看2xx代码.确切地说,哪种选择合适取决于您应用程序的语义.

So by process of elimination, which are looking at the 2xx codes. Exactly which would be a good fit depends on the semantics of your application.

因为这不是一个DELETE调用,所以我可能不会使用204 No Content,这可能是唯一的好选择.不是说没有内容.

Since, this is not a DELETE call, then I probably wouldn't use 204 No Content, which is probably the only good alternative. It's not that there's no content.

有内容:找到0个结果".没有搜索结果时,Google不会向您显示空白页.

There is content: "0 results found". Google doesn't show you a blank page when there are no search results.

因此,我们得出了200,同时还返回了一个有意义的身体.如果要返回原始结果,则可能需要考虑将它们包装在搜索结果对象中以提供一些元数据.

So we arrive at 200, as well as returning a meaningful body. If you were returning raw results, then you might want to consider wrapping them in a search-results object to provide some meta-data.

啊!因此,等等,如果您不是在显示搜索结果,而是在指示RESTful资源的集合呢?

Ah! So wait, what if instead of search results, you are indicating a collection of RESTful resources?

GET /items

在这种情况下,我仍将返回200,并显示没有物品的正文.

In this case, I would still return a 200 with a body that says there are no items.

如果您要检索特定资源怎么办?

What if, you were trying to retrieve a particular resource?

GET /items/1234

在这种情况下,是的,您想暗示项目1234不存在,并且应该返回404.

In this case, yes, you want to imply that item 1234 does not exist, and you should return a 404.

这篇关于休息服务返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆