使用GET参数的REST API [英] REST API using GET Params

查看:65
本文介绍了使用GET参数的REST API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有以下服务器资源:

Say we have the following server resource:

api.example.com/event/1

哪个返回任意资源,例如:

Which returns some arbitrary resource, say:

{
    id: 1,
    details: {
        type: 'webinar',
        ....
    },
    attendees: [
        {
            user_id: 1,
            first_name: 'Bob'
            ...
        },
        ...
    ]
}

对于客户而言,仅获取事件的事件详细信息而不是参与者列表的请求可能很有用.

It might be useful for a client to make a request to get just the event details of the event but not the list of attendees.

如果客户需要两个资源,是否最好为资源提供两个单独的URL并强制两个单独的请求?

Is it better to provided two separate URLs for the resources and force two separate requests if a client wants both resources?

api.example.com/event/{event_id}
api.example.com/attendees/{event_id}

或者提供相同的两个端点更好,但是可以选择让第一个端点支持GET参数以打开或关闭与会者列表

Or is it better to offer the same two endpoints, but optionally have the first one support a GET param to toggle the attendee listing on or off

api.example.com/event/{event_id}?listAttendees={true|false}
api.example.com/attendees/{event_id}

listAttendees 参数将使表示形式返回与会者列表的地方.

Where the listAttendees parameter will either have the representation return the attendee list or not.

允许GET参数更改从特定URL返回的表示形式是一种常见的做法吗?

Is it an common practice to allow GET params to change the representation returned from a specific URL?

推荐答案

我想说的是,在REST中最正确的方法是使用不同的媒体类型或媒体类型参数,但是由于大多数人没有为了不使用自定义媒体类型,我经常使用我称为缩放协议的东西.这个想法是,您有一个带有数字值的 zoom expand 参数,并且它递归包含子实体,将参数减小到零.

I'd say the most correct way to do that in REST would be with different media-types, or media-type parameters, but since most people don't use custom media-types, I often use something I call the zoom protocol. The idea is that you have a zoom or expand parameter, with a numeric value, and it recursively includes the children entities, decreasing the parameter until it reaches zero.

所以,这样的请求:

GET api.example.com/event/1

返回事件资源的普通表示形式,而不嵌入任何内容.这样的请求:

Returns the plain representation for the event resource, without embedding anything. A request like:

GET api.example.com/event/1?zoom=1

将包括事件的直接子对象(在您的情况下,包括参加者).在此之后:

Would include the immediate children of event, in your case, the atendees. Following on that:

GET api.example.com/event/1?zoom=2

将包括事件的直系子女,参加者的直系子女.

Would include the immediate children of event, the immediate children of atendees.

为回答您的问题,在REST中,整个URI是一个原子标识符,因此参数是URI的一部分.如果您使用的内容无法以相同的方式解释URI,那么这可能是个问题,例如旧的缓存服务器不会使用查询字符串来缓存URI.

To answer your question, in REST the whole URI is an atomic identifier, so the parameters are part of the URI. That can be a problem if you're using something that won't interpret URIs in the same way, like old cache servers who won't cache URIs with a querystring.

这篇关于使用GET参数的REST API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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