opensas
opensas

Reputation: 63555

standard way to represent a foreign key relation in a json rest web service

I have a Wine entity which is related to a country in a one to many relation (one country - many wines)

I can think of two ways to represent this in a json web service:

One is just including the whole country in a json

{
  id: 76,
  code: "FR",
  name: "France"
}

{
  id: 79,
  name: "Bordeaux",
  country: {
      id: 76,
      code: "FR",
      name: "France"
    },
  year: "2005"
}

the other is including each country property to the same level, with a prefix

{
  id: 79,
  name: "Bordeaux",
  countryId: 76,
  countrCode: "FR",
  countryName: "France"
  year: "2005"
}

In any case, when updating or creating a new wine, I will just save the country id, I won't allow to modify a country from the endpoint of wines

The second approach would be easier to implement (I would have a join view on the db, and the serializer would just transform every field to json), but I think the first one is more elegant

Just wanted to know if there's any standard for this kind of situation and in case there isn't what is the more common approach...

ps: I don't mean to start a debate on the "restfullness" of the solution, just looking for a smart an simple way to handle this relation...

Upvotes: 8

Views: 11798

Answers (2)

Roy Truelove
Roy Truelove

Reputation: 22466

In your case, country is small enough to consider nesting it every time. This is not always the case, though, and there is no standard that I've found on handling this.

I've done this with a custom reference type:

{
    "id": 79,
    "name": "Bordeaux",
    "country": {
        "ref": {
            "id": 76,
            "uri": "/country/76"
        }
    },
    "year": "2005" }

Some helpful ideas here as well.

Upvotes: 6

mgonto
mgonto

Reputation: 6595

JSon isn't there to have Foreign Keys. That's something that is related to RDBMS. In my opinion, JSon should show everything nested in itself.

MongoDB fortifies this opinion. IN MongoDB, you store everything as a JSon and the "FKs" are included in the same document. If you need FKs, then you don't need mongo and you don't need JSon in my opinion.

BTW, if you will always show the country, it doesn't make sense to make always two requestsac

Upvotes: -5

Related Questions