2
turbod
5y

On the office we have began to discuss which is best practice in a REST API when reference other objects.

Things like:

A)

```
{
"id": 1,
"field1": "value1",
"referenced": <id>
}
```

or

B)

```
{
"id": 1,
"field1": "value1",
"referenced": {
"id": <id>
}
}
```

I prefer B. What do you think?

Comments
  • 3
    How many identificators do you have? Only one I guess? What other referencing fields could you use in the future to refer to a particular, unique object?
  • 4
    I think I'd try to do it more verbose and more straight forward: "referenced_id": <id>. Later on you might have a need to add the whole object as `referenced`, so to prevent names' clash I'd go with as strict naming as possible.

    Unless your idea behind "referenced": {"id":<id>} was exactly that... Reusing the very same closure for either ID or the whole structure. But then again, with this ambiguity you'll get lost in checks' hell. How will you know whether you have sent out only ID? How would you differentiate btwn a response w/ only ID and a response w/ the full object that only has ID value and other fields are null? Unmarshaller will map them identicaly. As a result you'll have to make additional API calls to fetch the same structure by the ID and for what? Just to get the same structure with all null values but the ID.
  • 1
    A is a more "classic" approach. It's how the data would look if you were getting it from a SQL database.

    B is probably better if you intend to stick the entire contents of your referenced object into that reference, because "referenced" is always an object instead of sometimes being an ID and sometimes being an object.

    If it is strictly for reference, and the referenced object isn't going to be expanded inside the referencing object, I prefer A, but I can see the appeal of B.
  • 0
    @netikras well, the meaning of the response is completely defined. So you know if what you are getting is a reference to an object or the whole object.

    The point behind that is that later on you can also provide info about the relation itself.

    However I can see your point here that redundant data can lead to confusion. I didn't think about it.
Add Comment