how to pass json array in params to get rest api in nodejs

22 views Asked by At

I have one GET API which is having array in the input. I want to call that API through in my node.js project. I have tried many options but none worked. This is my REST Request.

let request = await Request.get(
    `url?arr=1234,1235`,
    {
    headers: {"Content-Type": "application/json" }
    }
    );

But getting bad request.

This is the CURL I received.

curl --location --request GET 'url' \
--header 'Content-Type: application/json' \
--data '
{
    "arr":["1234","1235"]
}

Please help.

I tried with POST request instead of GET.

I tried url?arr[]=1234,1235

I tried url?arr=["1234","1235"]

I tried url?arr="1234","1235"

I tried url?params={arr:["12551138844"]

2

There are 2 answers

0
Volen Todorov On BEST ANSWER

This could be done in several different ways. There is no set standard.

You could do it with url?arr=1234,1235, but you need to make sure that your backend parses the query parameter accordingly with something like arr = req.query.arr?.split(',').

Keep in mind that URL query parameters are just strings and parsing them is up to the backend. If you are using an API you should check its documentation. Different APIs have different URL parameter format requirements. If you make the API yourself you should make sure you are parsing the data correctly.

0
Yuvaraj M On

You have to use node:querystring module to build query params. I assume you are using commonJS if you use ESM simple change the import.

According to RFC 7231 section 3.1.5.5,

Content-Type HTTP header should be set only for PUT and POST requests, doesn't required for GET request

const queryBuilder = require('node:querystring');
const params = queryBuilder.stringify({arr:[1,2]}); // gives arr=1&arr=2

let request = await Request.get('url?'+params);

NODEJS DOC