1

I did some research about how REST APIs work and how to link resources via hypermedia. Most of the examples about linking resources is related to the response of the server. But I wonder how to reference to other resources when a certain resource should be updated.

Let´s take the simple resource of a person living at a specific location:

/api/persons/alice
{
  "name": "Alice",
  "location": {
    "id": 1,
    "links": {
      "self": "/api/locations/1"
    }
  }
}

Now I want to update the location to another existing location. But how do I represent that? Would I:

  1. refer to the id of the new location
PUT /api/persons/alice
{
  "name": "Alice",
  "location": 2
}
  1. refer to the URI of the new location
PUT /api/persons/alice
{
  "name": "Alice",
  "location": "/api/locations/2"
}
  1. anything else?
Franz Deschler
  • 2,456
  • 5
  • 25
  • 39

1 Answers1

1

HTTP PUT has remote authoring semantics - you should think of the payload as being the new representation of a document, being manipulated by some general purpose HTTP aware document editor.

GET /api/persons/alice HTTP/1.1
HTTP/1.1 200 OK
Content-Type: application/json

{
  "name": "Alice",
  "location": {
    "id": 1,
    "links": {
      "self": "/api/locations/1"
    }
  }
}
PUT /api/persons/alice HTTP/1.1
Content-Type: application/json

{
  "name": "Alice",
  "location": {
    "id": 2,
    "links": {
      "self": "/api/locations/2"
    }
  }
}
200 OK

The assumption here is that the consumer of your API is familiar with the schema here, and understands the semantics, which fields are optional, which are required, and so on.

(Getting this to work on a long time scale means investing effort in designing your schema well, choosing reasonable defaults, and so on).

Please observe this part of the PUT specification with care:

An origin server SHOULD verify that the PUT representation is consistent with any constraints the server has for the target resource that cannot or will not be changed by the PUT.... When a PUT representation is inconsistent with the target resource, the origin server SHOULD either make them consistent, by transforming the representation or changing the resource configuration...

...

An origin server MUST NOT send a validator header field (Section 7.2), such as an ETag or Last-Modified field, in a successful response to PUT unless the request's representation data was saved without any transformation applied to the body....

In other words, the server doesn't need to "store" the new representation as provided.

Community
  • 1
  • 1
VoiceOfUnreason
  • 52,766
  • 5
  • 49
  • 91