10.
Conditionally Serializing Fields with Groups
Keep on Learning!
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
If you liked what you've learned so far, dive in! Subscribe to get access to this tutorial plus video, code and script downloads.
Whoops, an error! Please, try again later.
2 Comments
@weaverryan First, I'd love to say thank you because your tutorial is outstanding. The quality is just superb..
Quick question, you mention this violates REST.
If you have an entity Battle like in your example, would you return the id of the programmer in it only?
For example:
From what I understand OPTION 1 is not RESTful
OPTION 1:
{
"id": 12,
"programmer": {
"id": 1,
"nickname": "UnitTester",
"avatar": 3
}
}
But, OPTION 2 would be?
OPTION 2:
{
"id": 12,
"programmer": {
"id": 1
}
}
Or maybe OPTION 3?
OPTION 3:
{
"id": 12,
"programmer_id": 1
}
What would the best RESTful way to handle OneToMany(s) like this?
Thank you!
Hey Anthony R.!
Sorry for my late reply! Symfony 4 comes out today (woo!) - it's been a bit busier around here than normal :).
So as far as "it violates REST" is concerned, the real "issue" is that normally, if you want to return different *representations* of a resource (e.g. a battle), then you would do it in some way that didn't involve the URL (e.g. by reading headers, etc). This is all a little bit fuzzy, honestly. But, the most common example is if you want to be able to return both the JSON or XML of a resource. The WRONG way to do it (via the rules of REST) is to change the URL somehow - e.g. /battles.json vs /battles.xml. That is because each URL should represent a unique resource... and these are 2 different URLs that are the *same* resource! Instead, you're suppose to tell your client to send an "Accept" header that tells the server what format they want. Then you have one URL, but that one URL can return different representations.
The same is basically true in this situation: returning different "amount" of embedded data is really just a different "representation" of the same resource. We're *always* returning a Battle resource, just with different "depth" of data (that's a different representation). REST would want us to do this in some way that didn't change the URL.
In other words, what is the most RESTful? Well, first, you should choose whether or not you want to embed your OneToMany data or not. And once you've decided this, do it consistently. Then, if you DO want to get fancy, you should make your client send a header (you can invent a header - X-API-DEPTH for example). And also, since REST should contain links, you would actually embed links to the OneToMany resources somewhere.
But in practice, headers are a bit more difficult (or at least, less obvious) for clients of your API to work with. That's why I kinda like the query parameter option. Rules be damned! :)
Cheers!
"Houston: no signs of life"
Start the conversation!