I am learning REST principles and I have a doubt on working with complex resources.
Let's say we have two resources, Foo and Bar, and for every Foo I must have a Bar. I want to make the dependency of bar from foo clear to developers using my API, so:
1) I will use links from Foo instances to Bar instances, and viceversa
GET /foos/1
Foo: {
'name': 'Foo instance',
'rel_bar': '/foos/1/bar'
}
GET /foos/1/bar
Bar: {
'name': 'Bar instance',
'rel_foo': '/foos/1',
}
2) I will use a URI templating that shows the dependency from Foo towards Bar (this is just for humans, as URI should be opaque for REST).
/foos --> Foo resource collection
/foos/{foo_id} --> An instance of a Foo resource
/foos/{foo_id}/bar --> The bar instance associated to the foo instance foo_id
So again, there are not bar without a corresponding foo.
Now I wish to create a Foo resource.
POST /foos
{
'name': 'Yet again another foo instance',
}
And let the server to create the corresponding Bar default (or empty) resource, so the next read will give:
GET /foos/2
{
'name': 'Yet again another foo instance',
'rel_bar': '/foos/2/bar'
}
And...
GET /foos/2/bar
{
'name': null, --> Let's say that null is the default value.
'rel_foo': '/foos/2/bar'
}
Is 'RESTfully correct' do this? My concerns are:
- is correct to let the server to automatically create a related resource? Or should I split the creation of Bar and Foo in two steps?
- is correct to POST a representation (just the 'name' attribute) and GET back a different one ('name' and the assigned 'rel_foo').
My personal thought is that since Bar has no meaning without a Foo, probably yes, I should let the server to create it.
Any idea?