# How to use Bitquery with Python

**URL:** <https://community.bitquery.io/t/how-to-use-bitquery-with-python/1163>\
**Category:** GraphQL Tutorials\
**Created:** [August 7, 2022, 7:57am UTC](https://community.bitquery.io/t/how-to-use-bitquery-with-python/1163 "2022-08-07T07:57:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![bitquery-support](https://avatars.discourse-cdn.com/v4/letter/b/71c47a/32.png) [@bitquery-support](https://community.bitquery.io/u/bitquery-support)\
**Post date:** [August 7, 2022, 7:57am UTC](https://community.bitquery.io/t/how-to-use-bitquery-with-python/1163/1 "2022-08-07T07:57:32Z")

</div>

# How to use Bitquery with Python

> **Table of Contents**
>
> 1. [Install Python](#install-python) 
> 2. [Why Python?](#why-python)
> 3. [Simple Use of Bitquery with Python](#simple-use-of-bitquery-with-python)
> 4. [A More Complex Use](#a-more-complex-use)
> 5. [References](#references)

## Install Python

_If you already have Python 3 installed, you can skip this._

Python for [Windows](https://www.python.org/downloads/)

Python for Linux (debian based): `sudo apt-get install python3 # some linux distros come with Python installed by default.`

## Why Python?

Python is a very easy language to learn and use, so it is ideal to make our first scripts to use Bitquery.  
  
  
We will use the following modules: `json`, `requests` and `datetime`. These three packages are installed by default in python 3.

- `json`: to be able to handle the output of our requests and to be able to parse the data correctly with python.
- `requests`: to make POST requests with python
- `datetime`: so that we can work with dates in UTC in an easy way.

## Simple Use of Bitquery with Python

To test we will make use of this [query](https://graphql.bitquery.io/ide/Get-Binance-15-Wallet-Balance)

```gql
{
  ethereum(network: ethereum){
    address(address: {is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549"}){
      balance
    }
  }
}

```

> In a nutshell, this query gets the ethereum balance of Binance 15 Wallet

#### How this query looks in Python?

```python
import requests
import json

query = """
{
  ethereum(network: ethereum){
    address(address: {is: "0x21a31ee1afc51d94c2efccaa2092ad1028285549"}){
      balance
    }
  }
}"""

json = {"query": query,}
headers = {"X-API-KEY": "API-KEY"}

request = requests.post("https://graphql.bitquery.io/", json=json, headers=headers)

if request.status_code == 200:
    data = request.json()
    print(data)
else: 
    print("Something unexpected happened.")

```

> The output should be something like this:

```python
{'data': {'ethereum': {'address': [{'balance': 26650.99761836389}]}}}

```

#### Ok perfect but how can I get the balance value?

You have to understand that the output we get is a dictionary, so to get the values we need to use the keys. There are two (or more) ways to get the value.

##### Simple way:

```py
print(data['data']['ethereum']['address'][0]['balance'])

```

> This is convenient when we only have one item. In this case it is, since I know that balance will always have only one item.

##### For Loop:

```py
for balance in data['data']['ethereum']['address']:
        print(balance['balance'])

```

> A for loop in these cases will always be useful if we have more than one item.

## A More Complex Use

In certain occasions we only need to make a “static” query, where there are no variables, in that case the best use is the one above.  
But in most of the cases we need to add variables.

To give an example we will use the following [query](https://graphql.bitquery.io/ide/Total-Gas-Used-In-A-Day-Ethereum):

```gql
query {
  ethereum(network: ethereum){
    transactions (options: {}, date: {since: "2022-08-01", till: "2022-08-03"}){
      date {date}
      count
      gasValue(in: USD)
      totalGasUsed: gas
      totalGasUsedInUSD: gasValue (in: USD)
    }
  }
 }

```

> This query will allow us to know how much gas has been used and how much has been spent in $.

As you can see here there are two very important variables that will affect our query which are `since` and `till`, these variables need to be changed, how do we do that in python? We could concatenate the string and put our variables in there, but this is not ideal so check the next snippet:

```py
import requests
import json
from datetime import datetime

query = """
query myQuery($dateutc: ISO8601DateTime){
  ethereum(network: ethereum){
    transactions (options: {}, date: {since: $dateutc, till: $dateutc}){
      date {date}
      count
      gasValue(in: USD)
      totalGasUsed: gas
      totalGasUsedInUSD: gasValue (in: USD)
    }
  }
}
"""

date = datetime.utcnow().strftime('%Y-%m-%d') # Here we get today in UTC

params = {"dateutc" : date} # Here we put the variables
json = {"query" : query, "variables": params}
headers = {"X-API-KEY" : "API-KEY"}

request = requests.post("https://graphql.bitquery.io/", json=json, headers=headers)

if request.status_code == 200:
    data = request.json()
    print(data)
else: 
    print("Something unexpected happened.")

```

##### What happened here?

We put the variables directly in the json of the request, this allows us more flexibility and readability of code.  
To set your variables you have to edit `params = {"dateutc" : date}` as well `query myQuery($dateutc: ISO8601DateTime)` here you have to specify the type of variable, for example: `String`, `[String!]`, `ISO8601DateTime`, you can check it on the [docs](https://graphql.bitquery.io/ide).

## References

If you have any specific problem with bitquery, maybe these links will help you:

[Bitquery Official Page](https://bitquery.io/)

[Bitquery Forum](https://community.bitquery.io/)

[Bitquery on Telegram](https://t.me/Bloxy_info)
