简体   繁体   中英

returning absolute vs relative URIs in REST API

suppose the DogManagementPro program is an application written in client/server architecture, where the customers who buys it is supposed to run the server on his own PC, and access it either locally or remotely.

suppose I want to support a "list all dogs" operations in the DogManagementPro REST API.

so a GET to http://localhost/DogManagerPro/api/dogs should fetch the following response now:

<dogs>
  <dog>http://localhost/DogManagerPro/api/dogs/ralf</dog>
  <dog>http://localhost/DogManagerPro/api/dogs/sparky</dog>
</dogs>

where I want to access it remotely on my local LAN, [the local IP of my machine is 192.168.0.33] what should aa GET to http://192.168.0.33:1234/DogManagerPro/api/dogs fetch?

should it be:

<dogs>
  <dog>http://localhost/DogManagerPro/api/dogs/ralf</dog>
  <dog>http://localhost/DogManagerPro/api/dogs/sparky</dog>
</dogs>

or perhaps:

<dogs>
  <dog>http://192.168.0.33/DogManagerPro/api/dogs/ralf</dog>
  <dog>http://192.168.0.33/DogManagerPro/api/dogs/sparky</dog>
</dogs>

?

some people argue that I should subside the problem altogether by returning just a path element like so:

<dogs>
  <dog>/DogManagerPro/api/dogs/ralf</dog>
  <dog>/DogManagerPro/api/dogs/sparky</dog>
</dogs>

what is the best way?

I've personally always used non-absolute urls. It solves a few other problems as well, such as reverse / caching proxies.

It's a bit more complicated for the client though, and if they want to store the document as-is, it may imply they also now need to store the base url, or expand the inner urls.

If you do choose to go for the full-url route, I would not recommend using HTTP_HOST, but setup multiple vhosts, and environment variable and use that. This solves the issue if you later on need proxies in front of your origin server.

I would say absolute URLs created based on the Host header that the client sent

<dogs>
  <dog>http://192.168.0.33:1234/DogManagerPro/api/dogs/ralf</dog>
  <dog>http://192.168.0.33:1234/DogManagerPro/api/dogs/sparky</dog>
</dogs>

The returned URIs should be something the client is able to resolve.

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