rest - 返回相同资源但使用不同 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.
肯定有人以前已经遇到过这个问题,但我在互联网上找不到任何东西。
解决方案
类似的概念称为部分响应,它提供了一个选项,让客户端可以使用查询参数指定哪些字段包含在响应中,例如:
/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
推荐阅读
- javascript - Firebase 身份验证需要两次“登录”调用
- mysql - mysql触发一对多关系
- angular - Angular 中的 CORS 策略已阻止访问 XMLHttpRequest
- javascript - While 循环仅在 draw() 函数 (P5.js) (P5.play) 中运行一次
- javascript - Wordpress 的 Javascript 和 JQuery 问题
- ruby-on-rails - 通过关联模型中的 form.collection_check_boxes 传递 ID
- wxpython - 使用 wxpython 的 atm 银行程序,我遇到的问题是在第一个面板中询问 id #我如何让它接受正确的 id
- copy - 在 Pycharm 中选择代码行很奇怪
- julia - 如何编写高阶函数来向给定函数添加方法?
- html - 引导网格偏移不居中