Amio.io
Amio.io

Reputation: 21585

REST: One to Many for GET via a foreign key

Relationships

Background

How to form the resource URL where we provide a robotId (foreign key) to retrieve its brain?

I could come up with this resource: GET /robots/:robotId/brain

I am not sure if using brain in singular is against REST conventions and practices. However, using GET /robots/:robotId/brains (brain in plurals) implies a collection will be returned but it will always have 1 item only.

Question

Can you advise me on a RESTful way?

Upvotes: 0

Views: 136

Answers (4)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57277

Can you advise me on a RESTful way?

REST doesn't care what spelling conventions you use for your resource identifiers.

Therefore, you should use whatever spellings make sense within your local context. That might mean, for your own convenience, that the spelling conventions that you use for your path segments are similar to those that you use when naming collections/tables in your data store. Or perhaps not - you could equally decide that, because the audiences differ, so too should the spelling conventions.

GET /robots/:robotId/brain
GET /robots/:robotId/brains
GET /brains/:robotId
GET /ee4fcf74-d494-4f90-8964-9e4d65aa61ef

These are all fine.

Stefan Tilkov's 2014 talk: REST: I don't Think it Means What You Think it Does may be helpful.

Upvotes: 1

abj1305
abj1305

Reputation: 665

You should have a rest end point which gives you the collection of all the brains of a robot. The uri should look like this :

GET /robots/:robotId/brains

Number of items the collection has should not matter.

If the rest end point is GET /robots/:robotId/brain, you are very much ignoring the fact that a robot might have multiple brains in the future and if very much possible if you database supports a one to many relationship.

To get 1 brain of a robot you can always keep scope for the below rest uri: GET /robots/:robotId/brains/:brainId Where brainId is the unique/primary key for a brain.

Upvotes: 0

a.cayzer
a.cayzer

Reputation: 289

If you have GET /robots/:robotId/brains this can still return a collection of size 1?

Upvotes: 0

Jonathan Delean
Jonathan Delean

Reputation: 1084

For me, you should have only 1 endpoint GET /robots/:robotId/brains, you will get all your collection, but your frontend have to processing your data like he want

Upvotes: 0

Related Questions