【问题标题】:What is the best practice for routing relationships in a REST api?在 REST api 中路由关系的最佳实践是什么?
【发布时间】:2017-11-04 06:21:43
【问题描述】:

假设我有两个对象,用户和约会,其中用户可能有一个或多个约会。

我很好奇我是否应该允许 API 的使用者通过 Appointments 控制器中的用户“过滤”。以下是我想到的 GET 操作调用:

Users Controller
GET
api/Users
api/Users/{userId}
api/Users/{userId}/Appointments
api/Users/{userId}/Appointments/{appointmentId}

Appointments Controller
GET
api/Appointments/
api/Appointments/{appointmentId}

我很好奇在 Appointments 控制器上为用户实现过滤器是否是一个好主意(良好做法)......所以上面的调用将变为:

Appointments Controller
GET
api/Appointments/{userId:int?}
api/Appointments/{appointmentId}

在上述调用中,我为 userId 添加了一个可选的查询字符串参数,该参数默认为 null。这将允许呼叫者获取所有约会,或通过 userId 获取约会。

我想我不太确定什么是具有关系的对象的最佳实践。

【问题讨论】:

    标签: c# asp.net-web-api routing attributerouting


    【解决方案1】:

    如果你想要简单,我建议

    用户 获取

    api/users
    api/user/{id}
    api/user/{id}/appointments
    

    约会 获取

    api/appointments
    api/appointment/{id}
    

    从外观上看,api/Appointments/{userId:int?} 读起来不太好,因为用户有约会,而约会只有一个用户。在端点 api/Appointments/{appointmentId} 的情况下,我不确定 AppointmentId 是什么,但如果它是一个 int 你将不得不做一些时髦的事情来查找约会或基于用户的用户int,在这种情况下 ID 可能相同。

    深入到对象树的深度可能会导致 url 结构混乱。

    【讨论】:

      猜你喜欢
      • 2020-04-23
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 2015-11-21
      • 2014-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      相关资源
      最近更新 更多