在找不到REST资源时返回404是否正确? [英] Is it correct to return 404 when a REST resource is not found?

查看:550
本文介绍了在找不到REST资源时返回404是否正确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的Jersey REST资源,如下所示:

Let's say I have a simple Jersey REST resource as follows:

@Path("/foos")
public class MyRestlet
        extends BaseRestlet
{

    @GET
    @Path("/{fooId}")
    @Produces(MediaType.APPLICATION_XML)
    public Response getFoo(@PathParam("fooId") final String fooId)
            throws IOException, ParseException
    {
        final Foo foo = fooService.getFoo(fooId);

        if (foo != null)
        {
            return Response.status(Response.Status.OK).entity(foo).build();
        }
        else
        {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    }

}

基于上面的代码,返回 NOT_FOUND 状态( 404 )是否正确,或者我应该返回 204 ,还是其他一些更合适的代码?

Based on the code above, is it correct to return a NOT_FOUND status (404), or should I be returning 204, or some other more appropriate code?

非常感谢提前!

推荐答案

在这种情况下,404响应非常典型且API用户很容易使用。

A 404 response in this case is pretty typical and easy for API users to consume.

一个问题是客户很难判断他们是否因为找不到特定实体而得到404,或者由于URI中的结构问题。在您的示例中, / foos / 5 可能会返回404,因为id = 5的foo不存在。但是,即使存在 id = 1 的foo, / food / 1 也会返回404(因为 foos 拼写错误)。换句话说,404表示构造错误的URI或对不存在的资源的引用。

One problem is that it is difficult for a client to tell if they got a 404 due to the particular entity not being found, or due to a structural problem in the URI. In your example, /foos/5 might return 404 because the foo with id=5 does not exist. However, /food/1 would return 404 even if foo with id=1 exists (because foos is misspelled). In other words, 404 means either a badly constructed URI or a reference to a non-existent resource.

当您有一个引用多个资源的URI时,会出现另一个问题。通过简单的404响应,客户端不知道找不到哪个引用的资源。

Another problem arises when you have a URI that references multiple resources. With a simple 404 response, the client has no idea which of the referenced resources was not found.

通过在响应中返回附加信息可以部分缓解这两个问题身体让呼叫者确切地知道未找到的东西。

Both of these problems can be partially mitigated by returning additional information in the response body to let the caller know exactly what was not found.

这篇关于在找不到REST资源时返回404是否正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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