REST request type for many to many relationship

别说谁变了你拦得住时间么 提交于 2019-12-11 10:33:51

问题


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



来源:https://stackoverflow.com/questions/32655046/rest-request-type-for-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!