2

I want to get some info from an JSON RPC API endpoint. the equivalent curl command is this:

curl 'https://api.mainnet-beta.solana.com' -X POST -H "Content-Type: application/json" -d '
  {
    "jsonrpc": "2.0", "id": 1,
    "method": "getTokenAccountBalance",
    "params": [
      "FYj69uxq52dee8AyZbRyNgkGbhJdrPT6eqMhosJwaTXB"
    ]
  }
'

it works and response is:

{"jsonrpc":"2.0","result":{"context":{"apiVersion":"1.13.5","slot":176510490},"value":{"amount":"68662508944","decimals":5,"uiAmount":686625.08944,"uiAmountString":"686625.08944"}},"id":1}

but when I want to make a call in my python script:

headers={'Content-type': 'application/json'}
            data1 =  {
              "jsonrpc": "2.0",
              "id": 1,
              "method": "getTokenAccountBalance",
              "params": [
                "FYj69uxq52dee8AyZbRyNgkGbhJdrPT6eqMhosJwaTXB",
              ]
            }
response = requests.post('https://api.mainnet-beta.solana.com',headers=headers,data=data1) 
print(response.text)

I get this:

{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}

what could be the issue?

  • @SembeiNorimaki because the first one is actual JSON (no trailing commas) while the second is a Python data structure. – Henry Woody Feb 07 '23 at 11:40

1 Answers1

3

That's because you should be using json argument of the requests.post function, not the data argument.

This is how you fix it:

import requests

headers = {'Content-type': 'application/json'}
data1 = {
  "jsonrpc": "2.0",
  "id": 1,
  "method": "getTokenAccountBalance",
  "params": [
    "FYj69uxq52dee8AyZbRyNgkGbhJdrPT6eqMhosJwaTXB",
  ]
}

response = requests.post('https://api.mainnet-beta.solana.com', 
                         headers=headers, 
                         json=data1)
print(response.text)

Notice the json argument of the requests.post.

fshabashev
  • 619
  • 6
  • 20
  • 1
    Thanks alot!! thought it will infer the type from header argument and didn't you can specifically choose json, I'm new to the requests library sorry – Fares_Hassen Feb 07 '23 at 11:43