【问题标题】:What is the best way to name REST resources when returning same resource but using different DTO?返回相同资源但使用不同 DTO 时命名 REST 资源的最佳方法是什么?
【发布时间】:2020-05-27 00:26:00
【问题描述】:

我很好奇返回相同资源但使用不同 DTO 的最佳方式是什么。 例如,我有一个用户类:

public class User {
   private String name;
   private String surname;
   private String age;
}

用户列表在 url 下可用:

/users

其他一些视图需要用户列表但没有年龄,所以,我想返回 UserDTO 列表。

public class UserDTO {
   private String name;
   private String surname;
}

定义url的正确方法是什么?

/userDtos - this is bad, because I can have more than one DTOs for representing users,
/users/dto - this is also bad
/users?name=true,surname=true - this one is also bad, it indicates that we are filtering the result, but we are not; we're just filtering fields.

肯定有人以前遇到过这个问题,但我在互联网上找不到任何东西。

【问题讨论】:

    标签: rest naming-conventions naming


    【解决方案1】:

    类似的概念称为部分响应,它提供了一个选项,让客户端使用查询参数指定要包含在响应中的字段,例如: :

    /user?fields=name,surename
    

    基本上,您可以为自己的查询语言定义一种语法来表示选择的字段。 HereGoogle Cloud API 是一些例子。

    通过将此概念带到更粗粒度的级别,您可以使用查询参数“view”来定义不同的预定义字段组合,例如:

    /users              //default view if no "view" query parameter is specified
    /users?view=admin   //maybe this view will not show age field
    /users?view=hr      //maybe this view only show the fields that are accessible to HR
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-23
      • 2019-07-01
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多