Quantcast
Channel: Question and Answer » json
Viewing all articles
Browse latest Browse all 148

Representing a “Belongs to” relationship in an API endpoint

$
0
0

Consider the following pseudo code models:

class Post
    int Id
    string Title
    int CategoryId
    Category Category

class Category
    int Id
    string Name

Note that Post belongs to Category. This is achieved via a CategoryId foreign key on Post. In the post model, there’s also a Category object.

So my questions are:

1. On a GET request for a post, what would your JSON look like?

A - Just the foreign key (this one seems a little inefficient if the value for the Category name is commonly needed)

{
  Id: 1,
  Title: 'My Title',
  CategoryId: 1
}

B - Just the nested object

{
  Id: 1,
  Title: 'My Title',
  Category: {
    Id: 1,
    Name: 'General'
  }
}

C - Both (same as the actual model)

{
  Id: 1,
  Title: 'My Title',
  CategoryId: 1,
  Category: {
    Id: 1,
    Name: 'General'
  }
}

2. Considering the above, what do you do for a PUT/POST?

I can’t seem to find any concrete examples of the best practice to represent this case. Any thoughts, guidance or discussion welcome!


Viewing all articles
Browse latest Browse all 148

Trending Articles