2017-11-23 12 views
1

私は既存のAPIのOpenAPI仕様を書いています。このAPIは、成功と失敗の両方についてステータス200を返しますが、応答構造は異なります。OpenAPI(Swagger)で同じHTTPステータスコードに対して異なる応答を定義する方法は?

ユーザーが正常にサインアップしている場合たとえば、サインアップAPIで、APIは、以下のJSONでステータス200を送信します。

{ 
    "result": true, 
    "token": RANDOM_STRING 
} 

重複ユーザーが存在する場合、APIは、ステータス200を送信次のJSONを使用します。

{ 
    "result": false, 
    "errorCode": "00002", // this code is duplicated error 
    "errorMsg": "duplicated account already exist" 
} 

この場合、レスポンスの定義方法は?

+0

応答が異なる場合は、異なる応答コードを使用しないでください。 –

+0

私はすでに存在するAPI用のドキュメントを構築しています。私はapiを編集することができません。なぜなら、apiが多数あり、アプリケーションがapiを使用しているからです。 –

+0

[swaggerで複数の404原因を指定するにはどうすればいいですか?](https://stackoverflow.com/questions/40640669/how-to-specify-multiple-404-causes-in-swagger) – Helen

答えて

1

これはOpenAPI 3.0では可能ですが、2.0では可能ではありません。

OpenAPI 3.0では、応答の代替スキーマを指定するためのoneOfがサポートされています。成功した応答や失敗した応答など複数の応答examplesを追加することもできます(ただし、これらの例は現在Swagger UIには表示されていません)。 OpenAPIを/闊歩2.0では

openapi: 3.0.0 
... 

paths: 
    /something: 
    get: 
     responses: 
     '200': 
      description: Result 
      content: 
      application/json: 
       schema: 
       oneOf: 
        - $ref: '#/components/schemas/ApiResultOk' 
        - $ref: '#/components/schemas/ApiResultError' 
       examples: 
       success: 
        summary: Example of a successful response 
        value: 
        result: true 
        token: abcde12345 
       error: 
        summary: Example of an error response 
        value: 
        result: false 
        errorCode: "00002" 
        errorMsg: "duplicated account already exist" 

components: 
    schemas: 
    ApiResultOk: 
     type: object 
     properties: 
     result: 
      type: boolean 
      enum: [true] 
     token: 
      type: string 
     required: 
     - result 
     - token 
    ApiResultError: 
     type: object 
     properties: 
     result: 
      type: boolean 
      enum: [false] 
     errorCode: 
      type: string 
      example: "00002" 
     errorMsg: 
      type: string 
      example: "duplicated account already exist" 

、あなただけのレスポンスコードごとに単一のスキーマを使用することができますので、ほとんどあなたが行うことができますが、オプションとして、様々なフィールドを定義し、モデルdescriptionや操作descriptionでそれらの使用法を文書です。

swagger: "2.0" 
... 

definitions: 
    ApiResult: 
    type: object 
    properties: 
     result: 
     type: boolean 
     token: 
     type: string 
     errorCode: 
     type: string 
     errorMsg: 
     type: string 
    required: 
     - result 
関連する問題