user1032531
user1032531

Reputation: 26281

REST endpoint to link entities

I have a cars entity and a people entity, and have REST endpoints that pretty much match:

curl -i -X POST -H "Content-Type:application/json" http://localhost:8888
     /cars/ -d '{"name":"Fuson","color":"red","foo":"bar"}'

curl -i -X POST -H "Content-Type:application/json" http://localhost:8888
     /people/ -d '{"name":"John","age":"27","foo":"bar"}'

I also have a many-to-many people_have_cars entity.

To add a record, what should the REST endpoint look like? For instance, the person and car be in the URL or in the body? If in the URL, any particular order? Should it be POST, PUT, or PATCH? What should it return?

What about same questions for deleting the many-to-many record?

Upvotes: 2

Views: 56

Answers (1)

Opal
Opal

Reputation: 84824

It depends on which side is the master in the relation. It sees that a single person can own multiple cars, so to view the cars you should introduce the following endpoint:

GET /people/{id}/cars/

And to add a new car to a given person:

POST /people/{id}/cars/

curl -i -X POST -H "Content-Type:application/json" http://localhost:8888
     /people/{id}/cars/ -d '{"carId": someCarId}'

You can also invert (or implement both) the relation and add persons to a particular car:

POST /cars/{id}/persons/

curl -i -X POST -H "Content-Type:application/json" http://localhost:8888
         /cars/{id}/persons/ -d '{"personId": somePersonId}'

Upvotes: 2

Related Questions