CodyEakins
CodyEakins

Reputation: 742

How should array query parameters be handled when a single value is expected?

I'm building an API, and I'm referencing OpenAPI for certain standards and best practices.

Let's say I have a paginated endpoint, /users. /users handles pagination using query parameters, offset and limit.

So if I want the first 50 users from my API, I would call GET /users?offset=0&limit=50.

Implementing this is very straight forward, but what if an API consumer calls the following:

/users?offset=0&offset=20&limit=50&limit100`

How should an API handle multiple values when only one value is expected for each query parameter? Should I throw an error? Should I only accept the first value for each parameter?

Is there anything in the latest OpenAPI spec that covers how this should be handled?

Upvotes: 2

Views: 1457

Answers (2)

aleung
aleung

Reputation: 10328

In the OpenAPI definition, if a query parameter allows multiple values, its schema should be defined as array:

  parameters:
    - name: q
      in: query
      schema:
        type: array
        items:
          type: string

When the schema of the parameter is single value, it's considered a violation of the schema for the client to send multiple values. But it is out of the scope of OpenAPI whether the server will tolerate this error.

parameters:
  - name: offset
    in: query
    schema:
      type:  integer
  - name: limit
    in: query
    schema:
      type:  integer

Upvotes: 1

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

In Node.js, When you have multiple values with the same keys, it returns an array of values like this:

{ offset: [ '0', '20' ], limit: [ '50', '100' ] }

It is available on the request object on query i.e request.query. It might create a range for offset and limit just speculating.

It could be the range for offset from 0-20 and the limit can be 50-100. The algorithm in open API must be able to handle it.

A better place should be to ask in an open API Q&A.

Upvotes: 0

Related Questions