sch0rschi
sch0rschi

Reputation: 35

swagger limit error codes of response

There is a swagger 2.0 file I am dealing with, where I want to specify that the error code from my response can only be USERNAME_VALIDATION_FAILED or EMAIL_VALIDATION_FAILED. This is due to a swagger-ui view of the swaggerfile where every response error can have the 20 error codes defined in the Error code enum. How to limit the possible error codes for a specific response?

In my swaggerfile there is the request

/register:
post:
  ...
  parameters:
      ...
  responses:
    ...
    400:
      description: Username or email validation failed, possible values for code are USERNAME_VALIDATION_FAILED, EMAIL_VALIDATION_FAILED
      schema:
        $ref: '#/definitions/Error'

and my Error looks like

Error:
type: object
properties:
  code:
    type: string
    enum:
      - USERNAME_VALIDATION_FAILED
      - EMAIL_VALIDATION_FAILED
      - USERNAME_EXISTS
      - ...

I would suggest something like

schema:
  $ref: '#/definitions/Error.code.of(USERNAME_VALIDATION_FAILED, EMAIL_VALIDATION_FAILED)'

Upvotes: 0

Views: 1691

Answers (1)

Helen
Helen

Reputation: 97827

You can't override the enum of a property, so you need a separate model:

RegistrationError:
  type: object
  properties:
    code:
      type: string
      enum:
        - USERNAME_VALIDATION_FAILED
        - EMAIL_VALIDATION_FAILED

Error:
  type: object
  properties:
    code:
      type: string
      enum:
        - USERNAME_VALIDATION_FAILED
        - EMAIL_VALIDATION_FAILED
        - USERNAME_EXISTS
        - ...

If the error models have common properties, you can "inherit" them from a base model to reduce code duplication:

BaseError:
  type: object
  properties:
    message:
      type: string

RegistrationError:
  allOf:
    - $ref: "#/definitions/BaseError"
    - type: object
      properties:
        code:
          type: string
          enum:
            - USERNAME_VALIDATION_FAILED
            - EMAIL_VALIDATION_FAILED

Error:
  allOf:
    - $ref: "#/definitions/BaseError"
    - type: object
      properties:
        code:
          type: string
          enum:
            - USERNAME_VALIDATION_FAILED
            - EMAIL_VALIDATION_FAILED
            - USERNAME_EXISTS
            - ...

Upvotes: 2

Related Questions