REST request type for many to many relationship

2019-08-15 05:55发布

问题:

Table structure

session
-------------------------
id | name | date
-------------------------

speaker
-------------------------
id | name 
-------------------------

session_speaker
-------------------------
session_id | speaker_id 
-------------------------

Request methods in place

a) GET /speakers (all speakers)

b) GET /speakers/:id (details on specific speaker)

c) GET /speakers/:id/sessions (list of sessions of a speaker)

Question

What type of request should I make to indicate I need not only the detail of the speaker but also it's sessions, essentially combining results of call (b) and (c) into one.

Also how is it done in real commercial projects? The client makes two calls (b & c) or do they develop another REST endpoint hence combing the results of b & c in a single call?

Or should the client make two requests?

回答1:

In fact, you could specify as query parameters which fields you want to have within your response payload. Something like:

GET /speakers/someid?fields=firstname,lastname,age,sessions

Another approach (a better one) should be to leverage the header Prefer (see this link for the specification: https://tools.ietf.org/html/rfc7240) to specify which kind of details you want to have within your response payload:

  • return=minimal: only the speaker hints
  • include=sessions: speaker hints and his / her sessions

Here is a sample:

 Get /speakers/someid HTTP/1.1
 Host: api.example.org
 Content-Type: application/json  
 Prefer: include=sessions
 Vary: Prefer,Accept,Accept-Encoding

Irakli Nadareishvili wrote an awesome blog post on this subject: http://www.freshblurbs.com/blog/2015/06/25/api-representations-prefer.html.

Hope it helps you, Thierry