gattoman
gattoman

Reputation: 65

How to require at least one property in an object in OpenAPI 3.0?

I have this OpenAPI schema:

components:
  schemas:
    User:
      type: object
      required:
        - username
        - email
        - description
        - profile_icon
      properties:
        username
          type: string
        email
          type: string
          format: email
        description
          type: string
        profile_icon
          type: string

All of properties are required. This is for PUT /user/profile.

I will change this to PATCH /user/profile. Users send parameters just they only request to change. System validates that at least one parameter is required.

How can I describe one of [username, email, description, profile_icon] is required?

Acceptable example requests:

{
  "username": "Will Smith"
}
{
  "email": "[email protected]",
  "profile_icon": "aaaaa.png"
}

Not acceptable example (error):

{}

The anyOf annotator is close but it seems to be only for $ref schemas, not properties.

https://swagger.io/docs/specification/data-models/oneof-anyof-allof-not/

Upvotes: 6

Views: 7326

Answers (1)

Helen
Helen

Reputation: 97677

The easiest way to require at least 1 property in an object is to use minProperties: 1.

    User:
      type: object
      minProperties: 1   # <--------
      properties:
        username:
          type: string
        ...

Upvotes: 12

Related Questions