REST API 404:错误的 URI 或缺少资源? [英] REST API 404: Bad URI, or Missing Resource?

查看:40
本文介绍了REST API 404:错误的 URI 或缺少资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建 REST API,但遇到了问题.

I'm building a REST API, but I've encountered a problem.

似乎在设计 REST API 时公认的做法是,如果请求的资源不存在,则返回 404.

It seems that accepted practice in designing a REST API is that if the resource requested doesn't exist, a 404 is returned.

然而,对我来说,这增加了不必要的歧义.HTTP 404 更传统地与错误的 URI 相关联.所以实际上我们是在说要么你到了正确的地方,但那个特定的记录不存在,或者互联网上没有这样的位置!我真的不确定哪个一个……"

However, to me, this adds unnecessary ambiguity. HTTP 404 is more traditionally associated with a bad URI. So in effect we're saying "Either you got to the right place, but that specific record does not exist, or there's no such location on the Internets! I'm really not sure which one..."

考虑以下 URI:

http://mywebsite/api/user/13

如果我收到 404 回复,是不是因为用户 13 不存在?还是因为我的网址应该是:

If I get a 404 back, is that because User 13 does not exist? Or is it because my URL should have been:

http://mywebsite/restapi/user/13

过去,如果记录不存在,我只是返回一个带有 HTTP 200 OK 响应代码的 NULL 结果.这很简单,在我看来非常干净,即使它不一定是公认的做法.但是有没有更好的方法来做到这一点?

In the past, I've just returned a NULL result with an HTTP 200 OK response code if the record doesn't exist. It's simple, and in my opinion very clean, even if it's not necessarily accepted practice. But is there a better way to do this?

推荐答案

404 只是 HTTP 响应代码.最重要的是,您可以提供响应正文和/或其他标头,其中包含开发人员将看到的更有意义的错误消息.

404 is just the HTTP response code. On top of that, you can provide a response body and/or other headers with a more meaningful error message that developers will see.

这篇关于REST API 404:错误的 URI 或缺少资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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