多对一关系的最佳 URL 结构

Best URL structure for relation many-to-one

我正在使用 Spring Boot(由 JHipster 生成)。

我有以下服务:

/api/market/
/api/market/:id

/api/product/
/api/product/:id

所有具有 GET、PUT、POST 和 DELETE 的对象。但我需要实施一项更具体的服务。

此服务应return市场内的所有产品X。但是要做到这一点,我想在这个调用中传递 URL 路径:/api/product?marketID=1,但我必须在市场 table 中创建一个 select 然后得到产品(通过 market_id 字段仅在一个 table 中搜索会更容易)。

不知道这个URL是不是最好的结构,也是这样的搜索。我知道您可以在 table 上搜索特定字段,然后进行筛选,但我进行了测试,但无法获得关系字段。

通常,您希望 URL 是语义化的和可导航的。所以根据你已经得到的:

/api/market/:marketId/product

此外,通常建议使用复数形式,因此我会执行以下操作:

/api/markets/:marketId/products

我想就如何构建您的 API 提出建议,然后为您的问题提供一个可能的答案。

通常,RESTful API遵循复数-单数原则:给定所有市场(复数部分),找到 ID 为 5231422(单数部分)的市场。用 /api/{plural-noun}/{singular-identifier} 在你的 URL 中反映这一点。所以你的 API 最终会看起来更像这样:

/api/products  (all products in the system)
/api/products/:productId  (a single product in the system)
/api/markets  (all markets in the system)
/api/markets/:marketId  (a single market in the system)

回答你的问题,那么:我推荐你使用"Russian stacking doll"URL的设计。看来您的设计表明单个市场可以包含多个产品。因此,您可能会发现这种 URL 更清晰一些:/api/markets/:marketId/products,它获取该市场中的所有产品。