electrotype
electrotype

Reputation: 8816

Open API 3 - How to describe a query parameter that is an array of integers but can be a single item?

Using Open API 3.0.1, I'm trying to describe a query parameter of type "integer", lets say we call it ids, that can be alone or can be an array.

For example:

/my-endpoint?ids=111

or

/my-endpoint?ids=111&ids=222

I did try:

- name: ids
  in: query
  required: false
  schema:
    type: array
    items:
      type: integer

And I understand that style: form and explode: true are the default.

But when I validate this with actual requests (I use express-openapi-validate which is a wrapper around Ajv), I get those errors:

/my-endpoint?ids=111

"Error while validating request: request.query.ids should be array"

/my-endpoint?ids=111&ids=222&ids=333

"Error while validating request: request.query.ids[0] should be integer"

And If I use "string" instead of "integer":

- name: ids
  in: query
  required: false
  schema:
    type: array
    items:
      type: string

/my-endpoint?ids=111

"Error while validating request: request.query.ids should be array"

/my-endpoint?ids=111&ids=222&ids=333

Valid!

How should I describe this ids parameter, which must be integer values?

UPDATE: I now understand that any query parameters will be a string when deserialized by an Express server (which I use). But I'm still unable to have a single element array to work!

Upvotes: 4

Views: 3642

Answers (1)

electrotype
electrotype

Reputation: 8816

After the comment from @Helen, I did try another validation library, express-openapi-validator and now it works well with:

- name: ids
  in: query
  required: false
  style: form
  explode: true
  schema:
    type: array
    items:
      type: integer

With express-openapi-validate, the only way I've been able to make it work is using:

- name: ids
  in: query
  required: false
  schema:
    anyOf:
      - type: array
        items:
          type: string
          pattern: '^\d+$'
      - type: string  
        pattern: '^\d+$'

So I suggest you use express-openapi-validator with an Express server.

Upvotes: 4

Related Questions