'REST response - should I put the URL of the new resource in the header, body, or both?
I have put together an API that responds to a POST request by putting the content of the new resource in the response body, and the URL of the new resource in the Location HTTP response header.
Sample request:
POST /api/v1/widgets HTTP/1.1
Content-type: application/json;
Accept: application/json;
{
"name": "[email protected]",
"price": "10",
}
Sample response:
HTTP 201 Created
Location: http://example.com/api/v1/widgets/123456
{
'widget':
{
'id': "123456",
'created': "2012-06-22T12:43:37+0100",
'name': "[email protected]",
'price': "10",
},
}
Someone has raised an issue that the URL should also be in the body of the response. Is there a best practice on this?
Solution 1:[1]
There is a reason for not putting the location (URL) of the newly created resource) in the body: the URL is metadata needed for the message interaction among service consumers and services, it's not "business data". There is a SOA Design Pattern called "Messaging Metadata" that suggests that URLs, security credentials, correlation identifiers, transaction IDs and other messaging and composition context data should be placed in headers, not in the body of the messages. Indeed, http already provides the standard header Location for that.
OTOH, if your REST service uses HATEOAS the response may contain one or more URLs that are direct links to operations you want to offer for consumers to dynamically bind and call.
I think having the URL in both header and body is the worst solution. Redundant data is prone to inconsistency in the long run.
Solution 2:[2]
Just to add to this old topic
This seems to be a RFC defined standard so some clients may rely on this - didn't test how browsers will behave, but I would say that 201 + Location header will cause the redirect (to the Location resource) as in case of 301, 303 and 307.
see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
or RFC:
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2
On other hand, most of API clients will use some kind of 'fetch' functionality without following redirects. The data will be expected to be in the body (not URLs of resources, but some kinds of IDs)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Paulo Merson |
| Solution 2 | Fis |
