Skip to main content

Package Test PyPI Latest Release PyPI - Downloads Package Status License Made by Five Binaries Maintained by Mathias Frohlich

blockfrost-python


A Python SDK for Blockfrost.io API

Getting started • Installation • Usage


Getting started

To use this SDK, you first need login into blockfrost.io and create your project to retrieve your API key.


Installation

PyPI Latest Release

pip install blockfrost-python

Usage

Using the SDK is pretty straight-forward as you can see from the following examples.

Cardano

from blockfrost import BlockFrostApi, ApiError, ApiUrls

api = BlockFrostApi(
    project_id='YOUR API KEY HERE',  # or export environment variable BLOCKFROST_PROJECT_ID
    # optional: pass base_url or export BLOCKFROST_API_URL to use testnet, defaults to ApiUrls.mainnet.value
    base_url=ApiUrls.testnet.value,
)
try:
    health = api.health()
    print(health)   # prints object:    HealthResponse(is_healthy=True)
    health = api.health(return_type='json') # Can be useful if python wrapper is behind api version
    print(health)   # prints json:      {"is_healthy":True}
    health = api.health(return_type='pandas')
    print(health)   # prints Dataframe:         is_healthy
                    #                       0         True


    account_rewards = api.account_rewards(
        stake_address='stake1ux3g2c9dx2nhhehyrezyxpkstartcqmu9hk63qgfkccw5rqttygt7',
        count=20,
    )
    print(account_rewards[0].epoch)  # prints 221
    print(len(account_rewards))  # prints 20

    account_rewards = api.account_rewards(
        stake_address='stake1ux3g2c9dx2nhhehyrezyxpkstartcqmu9hk63qgfkccw5rqttygt7',
        count=20,
        gather_pages=True, # will collect all pages
    )
    print(account_rewards[0].epoch)  # prints 221
    print(len(account_rewards))  # prints 57

    address = api.address(
        address='addr1qxqs59lphg8g6qndelq8xwqn60ag3aeyfcp33c2kdp46a09re5df3pzwwmyq946axfcejy5n4x0y99wqpgtp2gd0k09qsgy6pz')
    print(address.type)  # prints 'shelley'
    for amount in address.amount:
        print(amount.unit)  # prints 'lovelace'

except ApiError as e:
    print(e)

IPFS

from blockfrost import BlockFrostIPFS, ApiError

ipfs = BlockFrostIPFS(
    project_id='YOUR API KEY HERE'  # or export environment variable BLOCKFROST_PROJECT_ID
)
file_hash = None
try:
    ipfs_object = ipfs.add('./README.md')
    file_hash = ipfs_object.ipfs_hash
    print(file_hash)
except ApiError as e:
    print(e)

try:
    with open('./README_downloaded.md', 'w') as file:
        file_data = ipfs.gateway(IPFS_path=file_hash).text
        file.write(file_data)
except ApiError as e:
    print(e)

Verifying Secure Webhook signature

Webhooks enable Blockfrost to push real-time notifications to your application. In order to prevent malicious actor from pretending to be Blockfrost every webhook request is signed. The signature is included in a request's Blockfrost-Signature header. This allows you to verify that the events were sent by Blockfrost, not by a third party. To learn more about Secure Webhooks, see Secure Webhooks Docs.

You can verify the signature using verifyWebhookSignature function.

Example:

# Example of Python Flask app with /webhook endpoint
# for processing events sent by Blockfrost Secure Webhooks
from flask import Flask, request, json
from blockfrost import verify_webhook_signature, SignatureVerificationError

SECRET_AUTH_TOKEN = "SECRET-WEBHOOK-AUTH-TOKEN"

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    if request.method == 'POST':
        # Validate webhook signature
        request_bytes = request.get_data()
        try:
            verify_webhook_signature(
                request_bytes, request.headers['Blockfrost-Signature'], SECRET_AUTH_TOKEN)
        except SignatureVerificationError as e:
            # for easier debugging you can access passed header and request_body values (e.header, e.request_body)
            print('Webhook signature is invalid.', e)
            return 'Invalid signature', 403

        # Get the payload as JSON
        event = request.json

        print('Received request id {}, webhook_id: {}'.format(
            event['id'], event['webhook_id']))

        if event['type'] == "block":
            # process Block event
            print('Received block hash {}'.format(event['payload']['hash']))
        elif event['type'] == "...":
            # truncated
        else:
            # Unexpected event type
            print('Unexpected event type {}'.format(event['type']))

        return 'Webhook received', 200
    else:
        return 'POST Method not supported', 405



if __name__ == "__main__":
    app.run(host='0.0.0.0', port=6666)

Development

Install dependencies

pip install -r requirements.txt
pip install -r test-requirements.txt

Install package

 pip install .

Run integration and unit tests:

pytest

For integration tests you need to set env variable BLOCKFROST_PROJECT_ID_MAINNET

Release workflow

To release the package create a new release via GitHub releases. This action triggers the automated release workflow that packages and uploads the distribution to PyPI.

Metadata

Release files for blockfrost-python 0.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for blockfrost-python 0.7.0
File Size Uploaded
blockfrost_python-0.7.0.tar.gz 49.3 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for blockfrost-python 0.7.0
File Interpreter ABI Platform
blockfrost_python-0.7.0-py3-none-any.whl Python 3 none any Details

Total release size: 81.8 kB

Release files / blockfrost_python-0.7.0.tar.gz

Download URL blockfrost_python-0.7.0.tar.gz
Size 49.3 kB
Tags Source
SHA-256 checksum
How to use checksums
79a5904fcda56a01b1c5cca3f493e233f6e6ac78f48b96a232842ee826bd2db2
BLAKE2b-256 checksum
How to use checksums
ed6b3ac3ab86990f3c81dff47c015b534a0dae5795b1ae037333fdc5473e5d67
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.7

Release files / blockfrost_python-0.7.0-py3-none-any.whl

Download URL blockfrost_python-0.7.0-py3-none-any.whl
Size 32.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
54eb2693af99d2894c33cea844d888b68187250288d48f8b1e2d79d44f810daf
BLAKE2b-256 checksum
How to use checksums
22ef76c3f6e985c446d609d4aebecf22df5f48b94fead1fc7e1058389ccde077
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.7

Release history Release notifications | RSS feed

This release

0.7.0 This release

2 release files

0.6.0

2 release files

0.5.3

2 release files

0.5.2

2 release files

0.5.1

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.3

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page