E
E
Evgeniy Rybalko2020-01-14 11:51:41
Software design
Evgeniy Rybalko, 2020-01-14 11:51:41

What is the correct way to use nested entities in a REST response?

Good afternoon. Can you please tell me how to properly use nested entities in a REST response?
For example:
There is a simple task creation service.
To create a task, make a POST request to the /rest/tasks endpoint

{
    "author_id": 2 
    "task": "blah blah"
}

Is it possible to also display a nested entity with a username? Is this the right approach?
for example:
/rest/tasks/1
{
    "id": 1,
    "author": {
        "id": 2,
        "username": "user"
     },
     "task": "blah blah"
}

If there are links to some additional sources/books on best practices, please indicate.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Shumov, 2020-01-14
@whereeaglesdare

Do not use. To do this, either think about HAL / HATEOAS or towards GraphQL. REST works for this case, but fits very poorly into the concept

V
Vladimir Shapovalov, 2020-01-31
@Nexen2

Yii2 implements the following built-in URL parser:
In the normal case, when requesting an endpoint, a flat json with data is returned back. The author will be a number (id). If you add ?expand=author to the URL, the engine will automatically query the database for information about the author and insert it as a subarray where the identifier was. Essno, there is a list of relays allowed / prohibited for deployment.
You can also close it like this: expand=affor,affor.comments, then, in addition to the author, there will be a third level of nesting, subarraying the author's last comments (by default in Yii2 this is 20, again configured both on the backend and perpage in the URL).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question