Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating linked entities in REST api in Symfony

What is the proper way to create entity which will be linked to other ones? I can't find any source about how it should be done or how it is done in Symfony with FOSRestBundle bundle.

Background:

Lets have entity Car with entities of Wheel.

How to create Car with wheels in one request?
url: foo.com/cars POST
data: {car:{name="porsche", wheels:[{name:"fr"}, {name:"fl"}] }}
Is this the proper way how to do it? I read something about LINK and UNLINK http methods, but that would need send multiple requests in order to create all wheels and then link them together.

How to create wheel with belongs to multiple cars?
url: foo.com/wheels POST
data: {wheel:{name="super wheel", cars:[{id:1}, {id:2}] }}
In this situation, maybe using LINK header would be appropriate. But after reading this article, it would require parsing LINK headers for all POSTS and PUTS as well, making it expensive and bulky.

EDIT

I wrote to the author of mentioned article. Here is his answer:

I think you can send data containing both your wheels and cars in a single request. The most important thing here is to be pragmatic. There is no "clear" rules for building REST APIs.

LINK/UNLINK are useful when resources already exist, and you want to "link" them, in >other words, you want to add a "relation" between them, such as friendship for users, for instance.

About your second question, if cars exist, you can, first, create your wheel, and "link" >it to your cars. But it would mean two requests for this action (you can add multiple link headers in one request), or better you could send one POST request with link headers : one request to rule them all :p

Another option would be to reference the cars' ids into your wheel data. I think it's fine to do that too.

like image 592
Keo Avatar asked Jul 14 '14 21:07

Keo


1 Answers

We've had the same discussion just recently.

There is something to be said for clarity and clean architecture where you seperate our resources from relations and so on. There is also something to be said for not making 1000 requests and for putting together things that belong together.

Our final solution was very much like yours. The other solution would be to never include relations in resources when inserting them, and having a seperate API endpoint for creating relations (e.g. POST /cars/1/wheels/fl)

Which way you go mainly depends on your domain logic and app requirements. As soon as you have circular m:n relationships, you will have big trouble with the approach you (and we) choose. For more simple and hierarchical relations, it's a perfectly good way of doing it.

like image 191
Tom Avatar answered Nov 12 '22 21:11

Tom