Search code examples
apirestful-urlrest

REST API: Nested resource whose POST side effects create new (different) resources


I'm new to REST and trying to understand if the following approach is an accepted RESTful practise.

As a representative example, imagine in my domain I have a Route that is made up of a number of Legs. New locations can be added to a route, that create additional Legs in the Route. Another means of creating additional legs is selecting drivers. (The domain will create legs based on those the driver supports). So:

I can view a route, and a route and it's legs with the following resources:

GET /route/{route_id}
GET /route/{route_id}/legs

When adding legs to a route, I want to display a list of locations, that the user can select from. So I have implemented a locations resource. Locations are mostly static, and are provided from a separate system.

GET /route/{route_id}/locations

So the approach I wanted to take is:

POST /route/{route_id}/locations

When this resource is posted too (along with info like the arrival time etc. in the JOSN representation), it causes a side effect in the domain where new legs are created in the route.

For drivers it would be something like:

GET /route/{route_id}/drivers
POST /route/{route_id}/drivers

So after POSTing to:

/route/{route_id}/locations

The user would browse to:

GET /route/{route_id}/legs

And see the new legs.

Is this a viable approach to the above situation?

Another options would be:

GET /route/{route_id}/legs/locations
POST /route/{route_id}/legs/locations

Although conceptually this doesn't seem any different (the resources are just the same - the name of the URL is superfluous to REST).


Solution

  • I believe I may have an answer to my own question, which is that the above approach is correct. After some reading of the books: "RESTful Web Services" and "RESTful Web Services Cookbook" (both from O'Reilly) I came across what they refer to as "factory" resources.

    "A POST request is an attempt to create a new resource from an existing one. The existing resource may be the parent of the new one in a data-structure sense, the way the root of a tree is the parent of all its leaf nodes. Or the existing resource may be a special “factory” resource whose only purpose is to generate other resources. The representation sent along with a POST request describes the initial state of the new resource."

    From RESTful Web Services by Leonard Richardson; Sam Ruby

    So essentially locations are a factory resource that creates legs.

    Interested if anyone disagrees with my reading.