Make API calls to Bitquery in Python, JavaScript, Dart, Golang and PHP

In this tutorial, we are going to make API calls to Bitquery using a variety of programming languages which have utility across all technology domain.

Python

Python is a high-level, general-purpose programming language. Its design philosophy emphasizes code readability with the use of significant indentation. Its language constructs and object-oriented approach aim to help programmers write clear, logical code for small- and large-scale projects. Python is extensively used in :-

  • AI and Machine Learning
  • Data Analytics
  • Data Visualization
  • Web development
  • Game development
  • Software development tasks.

The following is an example of how we can call Bitquery GraphQL API using Python

import requests

def bitqueryAPICall(query: str):  
    headers = {'X-API-KEY': 'YOUR API KEY'}
    request = requests.post('https://graphql.bitquery.io/',
                            json={'query': query, 'variables': variables}, headers=headers)
    if request.status_code == 200:
        return request.json()
    else:
        raise Exception('Query failed and return code is {}.      {}'.format(request.status_code,query))


# The GraphQL query

query = """
query($network: BitcoinNetwork, $token: String){
  bitcoin(network: $network) {
    inputs(
      inputAddress: {is: $token}) {
      value
    }
    outputs( outputAddress: {is: $token}) {
      value
    }
  }
}
"""

variables = {
  "network": "bitcoin",
  "token": "18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX"
}

result = bitqueryAPICall(query) 
inflow = result['data']['bitcoin']['inputs'][0]['value'] 
outflow = result['data']['bitcoin']['outputs'][0]['value']
balance = outflow-inflow
print ("The balance of the Bitcoin wallet is {}".format(balance))

JavaScript

JavaScript, often abbreviated JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. Over 97% of websites use JavaScript on the client side for web page behavior, often incorporating third-party libraries. JavaScript is heavily used in:-

  • Adding interactive behavior to web pages. JavaScript allows users to interact with web pages.
  • Creating web and mobile apps. Developers can use various JavaScript frameworks for developing and building web and mobile apps.
  • Building web servers and developing server applications.
  • Game development.

The following is an example of how we can call Bitquery GraphQL API using JavaScript

const query = `
query($network: BitcoinNetwork, $token: String){
  bitcoin(network: $network) {
    inputs(
      inputAddress: {is: $token}) {
      value
    }
    outputs( outputAddress: {is: $token}) {
      value
    }
  }
}
`;

const variables = {
  "network":"bitcoin",
  "token":"18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX"
}

const url = "https://graphql.bitquery.io/";
const opts = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-KEY": "YOUR API KEY"
    },
    body: JSON.stringify({
        query,
        'variables':variables
    })
};

async function bitqueryAPICall(){
  const result = await fetch(url, opts).then(res => res.json())
  const inflow = result.data.bitcoin.inputs[0].value
  const outflow = result.data.bitcoin.outputs[0].value
  const balance = outflow - inflow
  console.log("The Balance of the particular Bitcoin wallet is", balance)
}

bitqueryAPICall()

Golang

Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. It is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency. Go is used in :-

  • Go is popular for cloud-based or server-side applications.
  • DevOps and site reliability automation are also popular ways to use Go.
  • Many command-line tools are written in Go.
  • Go is used in the world of artificial intelligence and data science.

The following is an example of how we can call Bitquery GraphQL API using Go

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)


func main() {
    jsonData := map[string]string{
        "query": `
                query($network: BitcoinNetwork, $token: String){
                  bitcoin(network: $network) {
                    inputs(
                      inputAddress: {is: $token}) {
                      value
                    }
                    outputs( outputAddress: {is: $token}) {
                      value
                    }
                  }
                }
        `,
        "variables": "{\"network\":\"bitcoin\", \"token\":\"18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX\"}",
    }
    jsonValue, _ := json.Marshal(jsonData)
    request, err := http.NewRequest("POST", "https://graphql.bitquery.io/", bytes.NewBuffer(jsonValue))
    request.Header.Set("Content-Type", "application/json")
    request.Header.Set("X-API-KEY", "YOUR API KEY")
    client := &http.Client{Timeout: time.Second * 10}
    response, err := client.Do(request)
    defer response.Body.Close()
    if err != nil {
        fmt.Printf("The HTTP request failed with error %s\n", err)
    }
    data, _ := ioutil.ReadAll(response.Body)
    fmt.Println(string(data))
}

Dart

Dart is a programming language designed for client development, such as for the web and mobile apps. It is developed by Google and can also be used to build server and desktop applications. It is an object-oriented, class-based, garbage-collected language with C-style syntax. Dart is used in:-

  • Flutter Cross-Platform Mobile Application Development
  • Web Development

The following is an example of how we can call Bitquery GraphQL API using Dart

import 'dart:convert';
import 'package:http/http.dart' as http;

void apiRequest(String url, String query) async {
  final gqlUrl = Uri.parse(url);
  final headers = {
    "X-API-KEY": "YOUR API KEY",
    "Content-Type": "application/json",
  };
  final bodyy = {
    "query": query,
    "variables": null
  };
  final body = jsonEncode(bodyy);
  final response = await http.post(
    gqlUrl,
    headers: headers,
    body: body,
  );
  Map<String, dynamic> data = jsonDecode(response.body);
  double inputs = data['data']['bitcoin']['inputs'][0]['value'];
  double outputs = data['data']['bitcoin']['outputs'][0]['value'];
  double balance = outputs-inputs;
  print('Balance of the Bitcoin wallet is $balance');
}

void main() async {
  String url = "https://graphql.bitquery.io/";
  String query = """
  {
    bitcoin {
      inputs(
        inputAddress: {is: "18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX"}
      ) {
        value
      }
      outputs( outputAddress: {is: "18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX"}) {
        value
      }
    }
  }
  """;
  apiRequest(url, query);
}

PHP

PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used, free, and efficient alternative to competitors such as Microsoft’s ASP. PHP is used in:-

  • PHP is a recursive acronym for “PHP: Hypertext Preprocessor”.
  • PHP is a server side scripting language that is embedded in HTML. It is used to manage dynamic content, databases, session tracking, even build entire e-commerce sites.

The following is an example of how we can call Bitquery GraphQL API using PHP

<html>
  <head>
    <title>PHP and Bitquery</title>
  </head>
  <body>
    <?php 
      $query='
      query($network: BitcoinNetwork, $token: String){
        bitcoin(network: $network) {
          inputs(
            inputAddress: {is: $token}) {
            value
          }
          outputs( outputAddress: {is: $token}) {
            value
          }
        }
      }
      ';
      $variables='
      {
        "network": "bitcoin",
        "token": "18cBEMRxXHqzWWCxZNtU91F5sbUNKhL5PX"
      }
      ';

      function bitquery ($query, $variables) {
        $data_string= json_encode(['query' => $query, 'variables'=> $variables]);
        $ch = curl_init('https://graphql.bitquery.io/');
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);                    
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);              
        curl_setopt($ch, CURLOPT_HTTPHEADER, array( 
            'Content-Type: application/json',         
            'X-API-KEY: YOUR API KEY'                 
        ));
        $result = curl_exec($ch);  
        return $result;
      } 

      $chart = bitquery($query, $variables);
      echo "$chart";
    ?> 
  </body>
</html>

Also Read

About Bitquery

Bitquery is a set of software tools that parse, index, access, search, and use information across blockchain networks in a unified way. We are crossing the ‘chain-chasm’ by delivering set of products that can work across blockchains. Our products include:

Coinpath APIs provide blockchain money flow analysis for more than 24 blockchains. With Coinpath’s APIs, you can monitor blockchain transactions, investigate crypto crimes such as bitcoin money laundering, and create crypto forensics tools. You can refer to this article to get started with Coinpath

Digital Assets API provides index information related to all major cryptocurrencies, coins, and tokens.

DEX API provides real-time deposits and transactions, trades, and other related data on different DEX protocols like Uniswap, SushiSawap, Kyber Network, Airswap, Matching Network, etc.

If you have any questions about our products, ask them on our Telegram channel or email us at hello@bitquery.io . Also, subscribe to our newsletter and stay updated about the latest in the cryptocurrency world.