D
D
DWS112020-12-02 11:42:48
RESTful API
DWS11, 2020-12-02 11:42:48

What is the best way to send related data through laravel rest api?

Greetings!
Composite question:
- tell me/share who gives related data via rest api, what are the best practices;
how to implement it in laravel.

Let the polygon be an online store that sells books.
We have the essence of the Book, which can have several genres, you can leave comments on it.

How I imagine it:
1) Give everything at once. But, if we only need books in a list (without genres, for example), then the answer will turn out to be redundant.
url /api/v0.1/books

"book": [
    {
        "id": "1",
        "author_id": "3",
        "genres": [
            {
                "id": "1",
                "name": "Fantasy"
            },
            {
                "id": "2",
                "name": "Drama"
            }
        ],
        "comments": [
            {
                "id": "1",
                "user_id": "35",
                "text": "Lorem ipsum"
            }
        ]
    },
]


2) Give through related resources. But here if we are talking about one book.
url /api/v0.1/books/1/genres /api/v0.1/books/1/comments
"book": [
    {
        "id": "1",
        "author_id": "3",
        "genres": [
            {
                "id": "1",
                "name": "Fantasy"
            },
            {
                "id": "2",
                "name": "Drama"
            }
        ]
    },
]


3) Give on demand. It seems like the method is devoid of drawbacks, but I can’t figure out how to implement it in code.
url /api/v0.1/books?expand=genres&comments
"book": [
    {
        "id": "1",
        "author_id": "3",
        "genres": [
            {
                "id": "1",
                "name": "Fantasy"
            },
            {
                "id": "2",
                "name": "Drama"
            }
        ],
        "comments": [
            {
                "id": "1",
                "user_id": "35",
                "text": "Lorem ipsum"
            }
        ]
    },
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2020-12-02
@DWS11

You can use Fractal instead of Lara's resources , where the third option is supported out of the box.
Well, or even use GraphQL.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question