带参数的 REST 资源

REST resources with parameters

这里有个问题。这是我们的简单域:有很多问题和答案,一个问题可能有几个答案,也可能没有。

示例:
问题:"Where can I get a pen?".
回答 #1:"You can buy a pen in a shop."
回答#2:"You can borrow it from a friend."

对于以下情况,可以使用以下 REST 资源:

GET /questions
GET /questions/{question_id}

GET /questions/{question_id}/answers
GET /questions/{question_id}/answers/{answer_id}

但是有些问题可能有如下参数:

"What is the distance between {location A} and {location B}?"
"What is the status of flight {flight_number}?"

将此类问题和答案表示为 REST 资源的最佳方式是什么?

好的,我想你可以构建这样的东西

GET /question /{questionid}?location=a&location2=b

GET /question /{questionid}?number=12345

但是,它要考虑很多事情。

谁定义了参数名称?是来电者提出问题吗?我想如果不了解参与与这些服务交互的参与者,就很难更具体。

抱歉,这并没有像我开始时希望的那样有用。 :)

考虑一下 POST 怎么样,我知道你正在回答这个问题,但同时你正在创建一个填写变量的问题。

在正文中以键值对(或字典)列表的形式提供变量。

您可以使用以下链接:

GET /questions/{question_id}/locationA:Zurich/locationB:Budapest/flightNumber:1234/answers

GET /questions/{question_id}/answers?locationA="Zurich"&locationB="Budapest"&flightNumber=1234

现在我不确定您是否需要此处的问题 ID。如果问题类型数量有限,那么您可以为每个问题添加一个路径。

GET /questions/distance/from:"Zurich"/to:"Budapest"

您可以根据问题标题自动生成:

GET /questions/what-is-the-distance/between:"Zurich"/and:"Budapest"

老实说,URI 结构对于 REST 服务并不重要,因为它仅供机器使用,开发人员也可能使用它来配置路由。 REST 客户端应该遵循链接而不是构建 URI (HATEOAS constraint)。所以大多数 API 都不是 REST,而且他们的大多数客户端也不是 REST 客户端...