2016-11-28 51 views
10

我有一個路徑,它爲每個http方法使用幾乎具有相同屬性的複雜模型。問題是我想爲PUT和POST的請求定義一些所需的屬性,而GET響應中不需要屬性(因爲服務器始終返回所有屬性,並且在文檔的其他地方提到了它)。具有不同所需屬性的重複使用模型

我創建了一個簡單的貓API來演示我所嘗試過的。這個想法是,對於GET響應,響應模型沒有任何標記,但是PUT的請求必須有一個貓的名字。

swagger: "2.0" 

info: 
    title: "Cat API" 
    version: 1.0.0 

paths: 
    /cats/{id}: 
    parameters: 
     - name: id 
     in: path 
     required: true 
     type: integer 
    get: 
     responses: 
     200: 
      description: Return a cat 
      schema: 
      $ref: "#/definitions/GetCat" 
    put: 
     parameters: 
     - name: cat 
      in: body 
      required: true 
      schema: 
      $ref: "#/definitions/PutCat" 
     responses: 
     204: 
      description: Cat edited 

definitions: 
    Cat: 
    type: object 
    properties: 
     name: 
     type: string 
    GetCat: 
    allOf: 
     - $ref: "#/definitions/Cat" 
    properties: 
     id: 
     type: integer 
    PutCat: 
    type: object 
    required: 
     - name 
    properties: 
     $ref: "#/definitions/Cat/properties" 

揚鞭編輯說,這是一個有效的規範,但name作爲要求都設置GET和PUT。 Swagger UI也一樣。

我也試過PutCat以下版本:

PutCat: 
    type: object 
    required: 
    - name 
    allOf: 
    - $ref: "#/definitions/Cat" 

但現在一切是可選的。

我無法弄清楚這一點。有沒有辦法正確地做到這一點?

編輯:

由於Helen正確提到的,我可以用readOnly解決與GET和PUT這種特殊情況下。

但是讓我們說,我添加breed財產必須提供(除了name屬性)爲PUT。然後我添加PATCH方法,它可以用來更新breedname而另一個保持不變,並且我不想根據需要設置那些。

回答

11

在您的示例中,您可以使用同一個模型同時用於GET和POST/PUT,僅在GET響應中使用的屬性標記爲readOnly。從spec

readOnly

聲明屬性爲 「只讀」。這意味着它可以作爲響應的一部分發送,但不能作爲請求的一部分發送。標記爲readOnly爲true的屬性不應位於已定義模式的必需列表中。默認值爲false。

該規範將如下所示:

get: 
     responses: 
     200: 
      description: Return a cat 
      schema: 
      $ref: "#/definitions/Cat" 
    put: 
     parameters: 
     - name: cat 
      in: body 
      required: true 
      schema: 
      $ref: "#/definitions/Cat" 
     responses: 
     204: 
      description: Cat edited 

definitions: 
    Cat: 
    properties: 
     id: 
     type: integer 
     readOnly: true 
     name: 
     type: string 
     breed: 
     type: string 
    required: 
     - name 
     - breed 

這意味着你必須把namebreed

{ 
    "name": "Puss in Boots", 
    "breed": "whatever" 
} 

GET /cats/{id}必須返回namebreed,也可能返回id

{ 
    "name": "Puss in Boots", 
    "breed": "whatever", 
    "id": 5 
} 
+0

謝謝,解決了這個例子中的問題。然而,我對我的例子有點粗心,並且更新了這個問題,即爲部分更新添加一個PATCH方法而不需要任何東西。 – NotNone

+0

@NotNone:我更新了答案。 – Helen

+0

謝謝,但現在看起來PATCH也需要名稱和品種(Swagger編輯器中都有星號)。這與原始問題中的問題相同。 我相信目前還沒有解決方案。 – NotNone

相關問題