Rest API: reasonable to create associated resources given a verbose representation?

StackOverflow https://stackoverflow.com/questions/16718702

  •  30-05-2022
  •  | 
  •  

문제

Take it that we have several collection resources.

I can create an instance resource on this collection:

POST /people
{
    "_links" : {
        "car" : {
            "href" : "/cars/66H8800"
        }
    }
    "name": "John"
}

However, would it be RESTfully reasonable to accept the following?

POST /people
{
    "_links" : {
        "car" : {
            "license" : "66H8800"
        }
    }
    "name": "John"
}

...which would result in the creation of the resources /people/1 (for example), and /cars/66G8800, if /cars/66G8800 did not already exist?

It seems that I'm beginning to mix the purpose of POST (create a new resource) and PUT (update/create a specific resource).

도움이 되었습니까?

해결책

Executive summary: Either is fine. I'd go with #1 with the caveat that you do it in at least two, possibly three requests. One to PUT the car, followed by another to POST the owner/driver. If you don't have the full resource data for the car beforehand, do a GET for that before the PUT, updating your PUT request body as necessary. If the GET returns 404, then just leave the unknown fields blank in your PUT, and define that your server will fill them in with default values (rather than, say, reject the PUT request).

Long answer:

REST does not dictate what the format of your message body should be.
The only constraints REST incurs upon you are:

  1. The uniform interface, in this case, HTTP's POST method. Using POST means you intend to append a new resource defined by the request body to the collection identified by the target URI. If doing so requires that the server must also create a resource elsewhere, then so be it.
  2. A documented, preferably common media type. Either use an existing media type (e.g. application/hal+json) or document the one you create.
  3. Use hypermedia (i.e. links) to advance the application state (browser window). In the request body, you can send whatever you like. It is the server's responsibility in its response to provide a hyperlink between car and person.
  4. The request must be self-contained. This means that you cannot, say, send one request to "set the current car to 66H8800" and then a second request to "create a driver for the currently set car". Doing this requires server state to be remembered between requests, which is forbidden in REST (as it breaks many things, like load balancing). It appears you are not doing this, but I can't tell from the code provided.

It is your media type that dictates whether or not a "license" key should exist. Choose or create one as you see fit.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top