MadeInDreams
MadeInDreams

Reputation: 2126

How to format axios GET call with nested params

I want to fetch an API

The call look like this;

 const instance = axios.create({
            method: 'GET',
            uri: 'https://api.compound.finance/api/v2/account',
            timeout: timeout,
            params: {
              block_number:'0',
              page_number:'1',
              page_size:'250',
              max_health: {
                value:'1'
                },
          
            },
            headers: {
              "Content-Type": "application/json",
            },
        
          });

The API spec https://compound.finance/docs/api

{
  "addresses": [] // returns all accounts if empty or not included
  "block_number": 0 // returns latest if given 0
  "max_health": { "value": "10.0" }
  "min_borrow_value_in_eth": { "value": "0.002" }
  "page_number": 1
  "page_size": 10
}

However the output URI contains some character to replace { } arround max_health value

The uri end up looking like this;

/api/v2/account?block_number=0&page_number=1&page_size=250&max_health=%7B%22value%22:%221%22%7D'

I have tried qs but it's not working as I expect.

I have tryed this to ;

 let params = {
    block_number:'0',
    page_number:'1',
    page_size:'250',
    max_health: {
      value:'1'
      }
    }

await instance.get('https://api.compound.finance/api/v2/account',JSON.stringify(params)).then( (response) => {...})

It gave me this error ;

TypeError: Cannot use 'in' operator to search for 'validateStatus' in {"block_number":"0","page_number":"1","page_size":"250","max_health":{"value":"1"}}

Any help would be appreciated.

Upvotes: 0

Views: 986

Answers (1)

MadeInDreams
MadeInDreams

Reputation: 2126

The fix; Use paramSerializer

 const instance = axios.create({
            method: 'GET',
            uri: 'https://api.compound.finance/api/v2/account',
            timeout: timeout,
            params: {
              block_number:'0',
              page_number:'1',
              page_size:'250',
              max_health: {
                value:'1'
                },
          
            },
            paramsSerializer: function (params) {
              return Qs.stringify(params, {arrayFormat: 'brackets'})
            },
            headers: {
              "Content-Type": "application/json",
            },
        
          });

Upvotes: 1

Related Questions