Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST api, POST entity with relationships?

Im having an issue where I cant decide how to procced on this matter.. and I need to know if there is any standard way to solve this.. or if you guys have any great input for this matter.

The thing is that I have started to build a very basic API for learning purpose The API is a simple Music store.. where the store has some Albums which requires and artist.

So the Relationship is Artist <--- 1 ----- * ---> Albums and for an album to exist its required that that the album has an artist. But the artist doesnt require and Album.

Now to the problem...

Due to this relationship if I want to create a new Album.. I would have to post the album data.. AND the entire Arist-data..not just the ID of th artist.. but the whole Artist.. which doesnt seem very effective if you ask me.. since that a whole lot of unnecessary.

So as I see it there is two ways to solve this... either I just post the entire album-data/object and allows the Artist-data for the object to only contain an ID which then reference to the artist.

So instead of posting:

{
"Name":"AlbumName",
"Description":"Some description for the album",
"ReleaseYear": "1992",
"Artist" {
    "Name":"Some artist",
    "Id":"12345",
    "Biography":"Lorem ipsum dolor sit amet"
    }
}

I would do this:

{
    "Name":"AlbumName",
    "Description":"Some description for the album",
    "ReleaseYear": "1992",
    "Artist" {
        "Id":"12345"
        }
    }

Option number two is to actually have a route/url thats specific for this... for instance: /api/artist/{artistid}/album And then simply post an album-object to that url..

But as I said.. Im really not sure of whats right and wrong here.. or is there any standard way of handling this?

Thanks in advance!

like image 265
Inx Avatar asked Mar 11 '13 14:03

Inx


1 Answers

I would suggest something like this.

POST /musicstore/artist/343/albums

{
    "Name":"AlbumName",
    "Description":"Some description for the album",
    "ReleaseYear": "1992",
}

The act of creating a resource as a child of the collection of albums for the artist 343 implicitly creates the relationship between the artist and the album. There is no need to specify it in the payload.

like image 176
Darrel Miller Avatar answered Sep 22 '22 17:09

Darrel Miller