简体   繁体   中英

OpenApi arrays and nested objects validation

I'm using OpenApi specification, this is an example of code that generates the class:

CreateUsersRequest:
      required:
        - userIds
      type: object
      properties:
        userIds:
          uniqueItems: true
          minItems: 1
          type: array
          items:
            type: string
            format: uuid

I want to prohibit sending the following request:

{
  "userIds": [
    ""
  ]
}
{
  "userIds": [
    null
  ]
}

In case I used javax.validation it would look like:

@NotNull 
private List<@NotEmpty UUID> userIds;

Is there any ways to do the same using api.yml file?

As indicated in the documentation :

OpenAPI 3.0 does not have an explicit null type as in JSON Schema, but you can use nullable: true to specify that the value may be null . Note that null is different from an empty string "" .

To prevent the empty string you could provide a pattern regex.

Please, try the following:

CreateUsersRequest:
      required:
        - userIds
      type: object
      properties:
        userIds:
          uniqueItems: true
          minItems: 1
          type: array
          items:
            type: string
            format: uuid
            nullable: false
            pattern: ^[a-z|\-]+$

Please, test the code carefully, I realized you used format: uuid , so I am not absolutely confident about the combination of format and pattern .

If necessary, you could try providing your own uuid type. For example:

Uuid:
    type: string
    pattern: '^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$'
    nullable: false

And:

CreateUsersRequest:
      required:
        - userIds
      type: object
      properties:
        userIds:
          uniqueItems: true
          minItems: 1
          type: array
          items:
            $ref: "#/components/schemas/Uuid"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM