14

Ive currently given the below code to get an array of values as query paramters (in Node-express, nodejs v14.17 and OpenAPI version 3.0.1),

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

but it send the req as an array of values(type is object) only if there are atleast two of them. For a single value, the type is string.How to always get req as array itself?

enter image description here

For example, if i give a single value say
"Hello", console.log(typeof(req.query["abcd"]),req.query["abcd"])
O/P: string Hello
but if i give "Hello" and "World",
O/P: object ['Hello','World']

2
  • Your array parameter definition is correct. Please post your controller code. What Node.js OpenAPI library do you use? Commented Jul 20, 2021 at 10:10
  • @Helen, hi, i have updated the question. Commented Jul 20, 2021 at 10:22

1 Answer 1

28

As this answer explains, when a query parameter gets passed a single value, e.g. ?abcd=hello, Express parses it as a regular value (i.e. string) rather than an array.

To pass a one-value array, you need to append [] at the end of the query parameter name, i.e. ?abcd[]=hello. This means you need to change the parameter name in your OpenAPI file:

       - name: abcd[]    # <------------
         description:  abcd
         in: query
         required: false
         schema:
           type: array
           items:
             type: string
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.