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

查看:1190
本文介绍了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不存在吗?或者是因为我的网址应该是

http:// mywebsite / restapi / user / 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 its 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天全站免登陆