返回相同资源但使用不同 DTO 时命名 REST 资源的最佳方式是什么?

What is the best way to name REST resources when returning same resource but using different DTO?

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

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

用户列表位于 url:

/users

一些其他视图需要用户列表但没有年龄,所以,我想要 return 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.

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

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

/user?fields=name,surename

基本上,您可以为自己的查询语言定义一种语法来表示选择的字段。 Here and Google 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