首页 > 解决方案 > REST API 设计 - 可选请求参数

问题描述

我已经编写了这个请求映射来通过它的 id 访问一张票:

@GetMapping(path = "/tickets/{ticketId}")
   @ResponseStatus(value = HttpStatus.OK)
    public ResponseEntity<List<TicketResponse>> getTicketsById(@PathVariable("ticketId") final Long ticketId

我打算添加多个查询参数来支持ticketType、ticketStatus等过滤。REST API 用户应该可以选择过滤任何或所有查询参数。

实现这一目标的 REST API 设计原则是什么?我应该添加新的请求参数来支持如下过滤吗?:

@GetMapping(path = "/tickets/{ticketId}")
   @ResponseStatus(value = HttpStatus.OK)
    public ResponseEntity<List<TicketResponse>> getTicketsById(@PathVariable("ticketId") final Long ticketId, @RequestParam("ticketType") final String ticketType, @RequestParam("ticketStatus") final String ticketStatus)

这种场景是否有 Spring 设计模式?Java builder 模式可用于参数 QueryParameter 对象的属性?

标签: springrestjpadesign-patterns

解决方案


你基本上有两个选择:

  1. 要么你把你所有的 RequestParams 作为方法参数,但是required=false就像@AmitKumar 写的那样。例子:@RequestParam(name="ticketType", required = false) String ticketType

  2. 将所有这些参数放入一个,比方说 FilterDTO 并将其作为参数 ( FilterDTO filter)。Spring 将确保使用您的 RequestParams 填充其字段。只需将您的 ticketType 和其他参数作为字段放入 DTO,它们将是可选的。例子:public ResponseEntity<List<TicketResponse>> getTicketsById(@PathVariable("ticketId") ong ticketId, FilterDto filter){}


推荐阅读