2016-09-20 64 views
1

例如,我可以創建一個車輛,並且必須給它一個可以是「汽車」或「飛機」的類型。汽車需要輪胎尺寸參數,而飛機需要翼展參數。關於REST API參數是否應該影響響應中所需的屬性的類似問題。REST API參數是否應該影響需要其他參數?

/vehicles: 
    post: 
     summary: Creates a vehicle 
     description: Adds a new vehicle of given type. 
     parameters: 
     - name: vehicle (what is the purpose of this????) 
      in: body 
      description: The vehicle to create. 
      schema: 
      required: 
       - type 
       - speed 
       - color 
      properties: 
       type: 
       type: string 
       speed: 
       type: interger 
       color: 
       type: string 
       wingspan: 
       type: string 
       tiresize: 
       type: string 
     responses: 
     204: 
      description: Vehicle succesfully created. 
     400: 
      description: Vehicle couldn't have been created. 

回答

2

儘管在實際中發生這種情況,但最好避免這種情況,因爲這會使您難以記錄API。如果您正在使用諸如Swagger之類的文檔技術,則不允許這些「有條件的必需」參數,這一點尤其如此。通過添加它們,您實際上是在您的API中添加了額外的語義,這些語義沒有記錄在Swagger文檔中。

更好的方法是,不要使用不同車型的「類型」參數,只需爲每種類型使用單獨的URL。這將允許您正確記錄每種車型的必需/可選參數。

/vehicles/automobile: 
    post: 
    parameters: 
     schema: 
     required: 
      - tyresize 
     properties: 
      tyresize: 
      type: string 
/vehicles/airplane: 
    post: 
    parameters: 
     schema: 
     required: 
      - wingspan 
     properties: 
      wingspan: 
      type: string 
+0

感謝tonicsoft。我可以在實踐中證明它發生在我正在做的事情上!進入Swagger後,我覺得我可能不應該,並感謝您的確認。注意......你的配置是否需要'name:automobile'和'in:body'?我正在閱讀https://apihandyman.io/writing-openapi-swagger-specification-tutorial-part-2-the-basics/,它總是添加一個名稱,但我不知道目的。謝謝 – user1032531

+0

很高興你發現它有幫助。是的,我相信配置總是需要一個名字(抱歉,我的草率的例子)。所有參數都需要一個名稱,就像面向對象代碼中的方法一樣。名稱是這樣的,以便您可以在使用API​​時實際提供參數的值:'curl -X POST -header'Content-Type:application/json'-d'{「vehicle」:....} ' – tonicsoft

+0

再次感謝tonicsoft。您的評論顯示爲'curl -X POST -header'Content-Type:application/json'-d'{「vehicle」:....}''。如果擴展你的意思是'curl -X POST -header'Content-Type:application/json'-d'{「vehicle」:{{「speed」:123,「color」:「blue」,「wingspan 「:321}}''http:// example.com/vehicles/airplane''。爲什麼不'curl -X POST -header'Content-Type:application/json'-d'{「speed」:123,「color」:「blue」,「wingspan」:321}''http://example.com/vehicles/airplane''工作,並通過對象成爲(對不起,我所知道的)PHP $ _POST超級全局變量? – user1032531

相關問題