首页 > 解决方案 > 返回相同资源但使用不同 DTO 时命名 REST 资源的最佳方法是什么?

问题描述

我很好奇返回相同资源但使用不同 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.

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

标签: restnaming-conventionsnaming

解决方案


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

/user?fields=name,surename

基本上,您为自己的查询语言定义语法来表示字段选择。这里谷歌云 API是一些例子。

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

/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

推荐阅读