Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API and eager loading rested resources

Tags:

rest

Imagine a resource such as Authors. An Author has multiple books, multiple pictures, etc.

In some pages of my app, I only need the surface author data such as name. In other pages, I need all the nested resources as well. How do I handle the loading of nested resources?

  1. Do I load everything in one call such that:
    GET /authors returns { name: x, books: { bookname: a, ... } }

  2. Accept an optional parameter that specifies the nested objects, such as:
    GET /authors?include=books&pictures

  3. Return just the surface author data then fetch the related resources in subsequent calls. However, this could lead to n+1 type queries, such as:
    GET /authors
    GET /author/1/images
    GET /author/1/books

Any insight appreciated

like image 884
recipherus Avatar asked Nov 10 '22 22:11

recipherus


1 Answers

I would go with the following REST-style URLs:

GET /authors - to get list of all authors

GET /authors/{authorId} - basic info about the concrete author in one request

GET /authors/{authorId}/detailed - detailed info about the concrete author in one request

Additionally, you could have the following methods to extract specific info about author:

GET /authors/{authorId}/images - get all images by author

GET /authors/{authorId}/images/{imageId} - get one image by author

GET /authors/{authorId}/books - get all books by author

GET /authors/{authorId}/books/{bookId} - get one book by author

Also I recommend to read REST resource naming conventions here.

like image 97
ialekseev Avatar answered Jan 04 '23 03:01

ialekseev