I am working on an REST API
and I am trying to understand how to deal with hierarchical resources.
Background
Let's start with a simple example. In my API I have Users, User profiles and Reviews.
- Users must have a User Profile associated (a User Profile corresponds to only one User)
- Users might have a Review associated (a Review corresponds to only one User)
User's resource representation should be:
User: {
"u1": "u1value", // User's attributes
"u2": "u2value",
...
"links": [{
"rel": "profile",
"href": "http://..." // URI of the profile resource
}, {
"rel": "review",
"href": "http://..." // URI of the review resource
}]
}
User profile resource representation should be:
UserProfile: {
"p1": "p1value", // Profile attributes
"p2": "p2value",
...
"links": [{
"rel": "owner",
"href": "http://..." // URI of the user resource
}]
}
Review resource representation should be:
Review: {
"r1": "r1value", // Review attributes
"r2": "r2value",
...
"links": [{
"rel": "owner",
"href": "http://..." // URI of the user resource
}]
}
Resources URIs could be:
http://api.example.com/users/{userid}
: access to the user resourcehttp://api.example.com/users/{userid}/profile
: access to the user's profile resourcehttp://api.example.com/users/{userid}/review
: access to the user's review resource
Resource creation: what's the correct way to create a user?
Now I want to create a new user:
POST http://api.example.com/users {"u1": "bar", "u2": "foo"}
and I get back the new userid = 42POST http://api.example.com/users/42/profile {"p1": "baz", "p2": "asd"}
PUT http://api.example.com/users {"u1": "bar", "u2": "foo", links: [{"rel": "profile", "href": "http://api.example.com/users/42/profile"]}
My concerns:
- What if something breaks between 1 and 2 or 2 and 3?
- In 3), should the server update automagically the links in the http://api.example.com/users/42/profile, to point to the correct owner?
- Updating link fields is the proper manner to create relationships? Or should I skip step 3) and let the system guess the relationships according to URI conventions? (I read on several books that URI should be considered as opaque.)