REST - API 为当前用户获取资源的设计

REST - API design to get resources for current user

我们有一个 FitnessClassesService 允许调度 fitness-training classes。每个 class:

有多个 演员

创建 class 时,所有演员也会添加到其中。培训师有一个应用程序,他们可以从中看到他们今天必须参加的 classes(以任何角色)。

我通过调用 POST /classes 创建了 classes。

什么是正确的 REST API,以便在培训师打开他们的应用程序时获取所有 classes。这些是我考虑的替代方案:

处理这个问题的规范方法是什么。

What would be the correct REST API for getting all classes for a trainer when they open their app

如果您想要 REST API,第一步是仔细考虑您的 resources

Any information that can be named can be a resource: a document or image, a temporal service (e.g. "today's weather in Los Angeles"), a collection of other resources, a non-virtual object (e.g. a person), and so on. In other words, any concept that might be the target of an author's hypertext reference must fit within the definition of a resource.

从概念上讲,“爱丽丝的日程”和“鲍勃的日程”是资源。 “我的日程安排”也是如此,但我们当然有代词先行问题。

有两种非常直接的方法来处理“我的日程安排”的经过身份验证的请求;您可以通过重定向到正确的资源进行响应,并且可以将正确资源的当前表示形式内联到您的响应中(使用元数据指示它的来源)。这些方法都是 fine.

(注意:RFC 7234 限制了经过身份验证的响应的 caching,这是它“很好”的部分原因)。

REST 不关心您对 URI 使用什么拼写(只要它符合 RFC 3986 中定义的生产规则)。所以这些都很好

/classes/actorId=alice
/classes?actorId=alice

/classes/alice
/classes?alice

Use a different URI.

还好。

您需要注意的一件事是 cache invalidation 与 URI 相关联;当您 POST 到 /classes 时,它会使 /classes 的本地缓存表示无效,但不会使 /myclasses 的本地缓存表示无效。这意味着当您将相同的信息编码到多个资源的表示中时,这些表示不一定会同步。

I PUT to /classes/{classId} , will it invalidate the cached response associated with /classes. Similarly, if I POST to /classes, will it invalidate the cached response associated with /classes/alice

两者都不是。相似标识符所暗示的层次结构是不真实的。您通过 link relations 描述 URI 之间的关系,而不是拼写,并且目前没有标准化的 link 关系表示“这些资源应该一起失效”。

When I PUT /classes/{classId}, shouldn't the cache for GET /classes be invalidated. Otherwise GET /classes may return a stale representation of /classes/{classId}

就通用组件而言,/classes/{classId}/classes 完全无关。标识符是 identifiers,而不是“identifiers and also implicit link relations”。

描述 link 之间关系的通用机制是 link relation. So if we wanted to announce to general purpose components that the changes to this resource also invalidate cached representations of that resource, we would need something like Linked Cache Invalidation

但是...那个草案在七年前就过期了,没有被采纳,我还没有找到替代它的方法。

这实质上意味着缓存失效的限制是您在设计资源模型时需要牢记的约束。如果信息 A 和信息 B 一起失效很重要,那么它们需要由相同的资源建模。

当然,你可以在你的有效载荷中包含缓存信息,这样自定义客户端就可以知道数据是无效的;您在记录模式中表达 link 关系,知道该模式的客户可以选择适当的操作。如果愿意,您甚至可以将该信息从消息的 body 提取到 header。但是由于 none 的标准组件知道你的新 header 的意思,所以他们都忽略它(换句话说,它只是噪音,直到我们有一个生产者和消费者都能理解的合同)。