简体   繁体   English

在 REST API 响应中返回指向资源位置的 URL 允许什么?

[英]What does returning URLs in a REST API response pointing to the location of resources allow for?

I've seen this a lot in "best practice" APIs such as Google's, but I don't quite know what the term to use is.我在 Google 等“最佳实践”API 中看到了很多这种情况,但我不太清楚要使用的术语是什么。

For example, you might have an Order object, which contains an invoice.例如,您可能有一个包含发票的订单 object。 But the invoice is not actually on the Order response.但发票实际上不在订单响应上。 Instead you receive something like:相反,您会收到以下内容:

Order: {
   Id: 1234,
   Invoice: "/order/invoices/5678
}

What is the benefit of this practice?这种做法有什么好处? What's it called, and where can I find more information about it?它叫什么,我在哪里可以找到有关它的更多信息? What does it allow me to do that I otherwise wouldn't be able to do?它允许我做什么,否则我将无法做到?

It is part of REST called HATEOS (Hypermedia as the Engine of Application State)它是 REST 的一部分,称为 HATEOS(超媒体作为应用程序状态的引擎)

The purpose is to enable the client to interact with related resources.目的是使客户端能够与相关资源进行交互。 So in this example the order links to an invoice.因此,在此示例中,订单链接到发票。 But it might also link to a customer for example.但它也可能链接到例如客户。 Often there is a separate block of related resources with links.通常有一个单独的带有链接的相关资源块。 At the same time there are plenty of "REST" API's that do not do this.同时有很多“REST”API 不这样做。 I think it is the least used aspects of REST.我认为是REST最少使用的方面。

I don't quite know what the term to use is我不太清楚该用什么词

You might be looking for "linking" vs "embedding"您可能正在寻找“链接”与“嵌入”

Linking:链接:

Order: {
   Id: 1234,
   Invoice: "/order/invoices/5678
}

Embedding:嵌入:

Order: {
   Id: 1234,
   Invoice: {
     Id: 5678,
     ...
   }
}

The tradeoffs between the two include complexity of the representations, number of round trips you need to make to collect "all" of the information, and caching of resources.两者之间的权衡包括表示的复杂性、收集“所有”信息所需的往返次数以及资源的缓存。

It's somewhat analogous to serving a web page with an image;这有点类似于为 web 页面提供图像; do you want the image to be a separate resource that has its own caching metadata, or do you want to embed the image representation directly into the HTML ?您是否希望图像成为具有自己的缓存元数据的单独资源,还是要将图像表示直接嵌入到 HTML 中


What you will sometimes see in resource models is to include two different resources for order;您有时会在资源模型中看到包含两种不同的订单资源; one using a link, the other using an embedded representation.一个使用链接,另一个使用嵌入式表示。

/order/1234
/order/1234?includeInvoice=true

Of course, including the same information into multiple resources has its own tradeoffs to worry about (cache invalidation is one of the two hard problems).当然,将相同的信息包含到多个资源中需要考虑其自身的权衡(缓存失效是两个难题之一)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM