簡體   English   中英

我們應該在 REST API 的路徑參數、查詢參數或 JSON 請求中使用枚舉常量嗎?

[英]Should we use enum constants in REST API's path-params, query-params or JSON requests?

問題是關於 REST API 的最佳實踐。

示例:我有一個以路徑參數作為狀態的 get API。

/api/{status}

現在,在代碼中,狀態被定義為一個枚舉(Status)。 只能有 3 個(或一些小的有限)可能的狀態值。

public enum Status {
    created,
    completed,
    cancelled
}

那么,我應該接受“狀態”作為字符串還是枚舉類型?

@Path("/api/{status}")
@GET
public Response get(@PathParam("status") String status) {}
// then I can check if it is a valid status

或者

@Path("/api/{status}")
@GET
public Response get(@PathParam("status") Status status) {}
// it will throw an exception if it is an invalid status

另外,我也想知道關於查詢參數和 JSON 請求的最佳實踐。

在 API 上使用枚舉,帶來更好的設計。 其原因與我們通常使用它們的原因相同。 具有它們的編程語言中的枚舉與 OpenApi 規范https://swagger.io/docs/specification/data-models/enums/之間存在兼容性,因此我看不出反對它們的好論據。

暫無
暫無

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

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