簡體   English   中英

帶有可選參數的 REST GET API - 設計和實現

[英]REST GET API with optional parameters - design and implementation

在我的虛擬圖書館中有一個 REST 端點來列出我們在那里擁有的所有書籍:

@GetMapping(path = "/books")
public List<Book> getBooks() {
    return bookService.findAllBooks();
}

他們說:“有時我們想在從 UI 請求時按圖書作者過濾該列表”

現在是:

  @GetMapping(path = "/books")
  public List<Book> getBooks(
      @RequestParam(value = "author", required = false) String author) {
    if (isEmpty(author)) {
      return bookService.findAllBooks();
    } else {
      return bookService.findBooksByAuthor(bookName);
    }
  }

現在他們說:“現在我們希望有時也能夠按年份過濾所有書籍”

所以我想……它會變成這樣嗎:

  @GetMapping(path = "/books")
  public List<Book> getBooks(
      @RequestParam(value = "author", required = false) String author,
      @RequestParam(value = "year", required = false) String year) {
    if (isNotEmpty(author)) {
      return bookService.findBooksByAuthor(author);
    } else if (isNotEmpty(year)) {
      return bookService.findBooksByYear(year);
    } else {
      return bookService.findAllBooks();
    }
  }

如果以后他們要求更多可選參數——我應該將這個 API 拆分到單獨的端點還是發明一些復雜和智能的搜索? 你怎么會去這里?

對於那些感興趣的人——我決定不要讓它像 Java 會議的解決方案那樣太酷。 所以解決方案是:

  1. 在一個端點接受參數作為@RequestParam 值

  2. 構建這些參數的映射(使它們類似於 json)

  3. 創建表示填充了部分參數的實體的搜索“探針”

  4. 使用 org.springframework.data.domain.Example 例如

    Example<Book> bookExample = Example.of(probe, ExampleMatcher.matchingAll())

  5. 使用org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example<S>)例如bookRepository.findAll(bookExample)

僅查找與傳入參數匹配的那些實體

答對了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM