简体   繁体   中英

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.

For example, you might have an Order object, which contains an invoice. 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)

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. I think it is the least used aspects of 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; 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 ?


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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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