Bitcoin Lab API Demo

Learn how to interact with the Bitcoin Lab API using a simple Python script.

Demo Script

import requests
import urllib.parse
import json

# ================================
# Configuration Variables
# ================================

# Base URL of the API server
BASE_URL = "https://api.researchbitcoin.net"               # Base URL

# API endpoint path
ENDPOINT_PATH = "/v1/supply_distribution/supply_coinbase"  # See https://api.researchbitcoin.net/docs for endpoints

# Query parameters for the API request
PARAMETERS = {
    "token": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",       # Replace with your actual token
    "date_field": "2024-12-01",                            # Specify the date in format YYYY-MM-DD
    "output_format": "json"                                # Desired response format (json or csv)
}

# Full API endpoint URL constructed by joining base URL and endpoint path
ENDPOINT = urllib.parse.urljoin(BASE_URL, ENDPOINT_PATH)

# ================================
# End of Configuration
# ================================

def make_api_request(endpoint, params, headers=None, timeout=10):
    """
    Makes a GET request to the specified API endpoint with given parameters and headers.

    Args:
        endpoint (str): The full URL of the API endpoint.
        params (dict): Dictionary of query parameters.
        headers (dict, optional): Dictionary of HTTP headers.
        timeout (int, optional): Timeout for the request in seconds.

    Returns:
        dict: Parsed JSON response from the API, or None if an error occurred.
    """
    try:
        # Make the GET request to the API with headers and timeout
        response = requests.get(endpoint, params=params, headers=headers, timeout=timeout)

        # Raise an exception for HTTP error codes (4xx and 5xx)
        response.raise_for_status()

        # Parse the JSON response
        data = response.json()
        return data

    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP error occurred: {http_err}")        # e.g., 404 Not Found
    except requests.exceptions.ConnectionError as conn_err:
        print(f"Connection error occurred: {conn_err}")  # e.g., DNS failure, refused connection
    except requests.exceptions.Timeout as timeout_err:
        print(f"Timeout error occurred: {timeout_err}")  # Request timed out
    except requests.exceptions.RequestException as req_err:
        print(f"An error occurred: {req_err}")           # Any other request-related errors
    except json.JSONDecodeError as json_err:
        print(f"JSON decode error: {json_err}")          # Response was not valid JSON

    return None


def main():
    """
    Main function to demonstrate API usage.
    """
    print("=== API Usage Demonstration ===\n")
    print(f"Endpoint: {ENDPOINT}")
    print(f"Parameters: {PARAMETERS}\n")

    # Make the API request
    response_data = make_api_request(ENDPOINT, PARAMETERS, headers={"Accept": "application/json"}, timeout=10)

    # Check if the response was successful
    if response_data is not None:
        print("=== API Response ===")
        print(json.dumps(response_data, indent=4))
    else:
        print("Failed to retrieve data from the API.")


if __name__ == "__main__":
    main()
Download Demo Script