Reputation: 9241
I'm designing a RESTful web service and am attempting to make proper use of hypermedia to establish relationships between resources. For some resources, the client needs to be able to assign a relationship to another resource, however it seems to me that requiring the client to generate a hyperlink and POST/PUT/PATCH/whatever this hyperlink into a resource has some drawbacks (more complexity for the client, security and load balancing concerns, etc.). I'm thinking that having the client send a simple ID and having the server generate the URL would be better.
Here are some completely contrived resources for a piano rental API to demonstrate my thinking.
GET http://company.com:9999/customers/42
{
"id" : 42,
"name" : "George P. Burdell",
"phone" : "555-555-5555",
"piano" : { "href" : "http://company.com:9999/pianos/101"}
}
GET http://company.com:9999/pianos/101
{
"id" : 101,
"make" : "Steinway",
"model" : "Model D"
}
Suppose a customer wants to rent a different piano.
The client sends a partial update such as:
PATCH http://company.com:9999/customers/42
{ "piano" : 202}
The server would then generate a proper url to the new piano resource and update accordingly:
GET http://company.com:9999/customers/42
{
"id" : ...,
"name" : ...,
"phone" : ...,
"piano" : { "href" : "http://company.com:9999/pianos/202"}
}
Edit: As I see it, clients directly updating hyperlinks can be problematic. Is this a RESTfully good solution, or is there a better one? Is this not even a problem at all? Also, real world examples of clients updating resource hyperlinks in some way would be great-- I haven't found any.
Upvotes: 2
Views: 126
Reputation: 6687
Your response are missing the links and forms required by the HATEOAS contraint of RESTful systems. For instance, if a customer wants to rent a different piano, then you can add a "rent" form on the piano response. For instance
GET http://company.com:9999/pianos/101
{
"self" : "http://company.com:9999/pianos/101",
"id" : 101,
"make" : "Steinway",
"model" : "Model D",
"rent" : {
"href" : "http://company.com:9999/pianos/101",
"method" : "post"
// you can add form parameters like from and to dates here
}
}
IMO this should create a "rental" resource, which would provide the many-to-many relationship between a piano and a customer. Then to allow customer to cancel a rental you can have a delete form on the rental agreement.
Here are a couple of good articles covering this:
Upvotes: 1