blockfrost-python


Nameblockfrost-python JSON
Version 0.5.3 PyPI version JSON
download
home_pagehttps://github.com/blockfrost/blockfrost-python
SummaryThe official Python SDK for Blockfrost API v0.1.37
upload_time2023-02-08 10:12:28
maintainer
docs_urlNone
authorblockfrost.io
requires_python>=3.7, <4
licenseApache-2.0
keywords blockfrost blockchain cardano ipfs
VCS
bugtrack_url
requirements requests
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![Package Test](https://img.shields.io/github/actions/workflow/status/blockfrost/blockfrost-python/package-test.yml?logo=GitHub&label=package%20test)](https://github.com/blockfrost/blockfrost-python/actions/workflows/package-test.yml)
[![PyPI Latest Release](https://img.shields.io/pypi/v/blockfrost-python.svg?logo=pypi&label=pypi%20latest)](https://pypi.org/project/blockfrost-python/)
[![PyPI - Downloads](https://img.shields.io/pypi/dm/blockfrost-python?logo=pypi&label=pypi%20downloads)](https://pypistats.org/packages/blockfrost-python)
[![Package Status](https://img.shields.io/pypi/status/blockfrost-python.svg)](https://pypi.org/project/blockfrost-python/)
[![License](https://img.shields.io/pypi/l/blockfrost-python.svg)](https://github.com/blockfrost/blockfrost-python/blob/master/LICENSE)
[![Made by Five Binaries](https://img.shields.io/badge/made%20by-Five%20Binaries-darkviolet.svg)](https://fivebinaries.com/)
[![Maintained by Mathias Frohlich](https://img.shields.io/badge/maintained%20by-Mathias%20Frohlich-blue.svg)](https://github.com/mathiasfrohlich)

<img src="https://blockfrost.io/images/logo.svg" width="250" align="right" height="90">

# blockfrost-python

<br/>

<p align="center">A Python SDK for Blockfrost.io API.</p>
<p align="center">
  <a href="#getting-started">Getting started</a> •
  <a href="#installation">Installation</a> •
  <a href="#usage">Usage</a>
</p>
<br>

## Getting started

To use this SDK, you first need login into to [blockfrost.io](https://blockfrost.io) create your project to retrieve
your API key.

<img src="https://i.imgur.com/smY12ro.png">

<br/>

## Installation

[![PyPI Latest Release](https://img.shields.io/pypi/v/blockfrost-python.svg)](https://pypi.org/project/blockfrost-python/)

```console
$ pip install blockfrost-python
```

<br/>

## Usage

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

### Cardano

```python
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

```python
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](https://blockfrost.dev/docs/start-building/webhooks/).

You can verify the signature using `verifyWebhookSignature` function.

Example:

```python
# 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)
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/blockfrost/blockfrost-python",
    "name": "blockfrost-python",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7, <4",
    "maintainer_email": "",
    "keywords": "blockfrost blockchain cardano ipfs",
    "author": "blockfrost.io",
    "author_email": "contact@blockfrost.io",
    "download_url": "https://files.pythonhosted.org/packages/a9/60/6701ac0588ba48dda821a1249aee447ceeb844601d00c509c17843a3af6e/blockfrost-python-0.5.3.tar.gz",
    "platform": null,
    "description": "[![Package Test](https://img.shields.io/github/actions/workflow/status/blockfrost/blockfrost-python/package-test.yml?logo=GitHub&label=package%20test)](https://github.com/blockfrost/blockfrost-python/actions/workflows/package-test.yml)\n[![PyPI Latest Release](https://img.shields.io/pypi/v/blockfrost-python.svg?logo=pypi&label=pypi%20latest)](https://pypi.org/project/blockfrost-python/)\n[![PyPI - Downloads](https://img.shields.io/pypi/dm/blockfrost-python?logo=pypi&label=pypi%20downloads)](https://pypistats.org/packages/blockfrost-python)\n[![Package Status](https://img.shields.io/pypi/status/blockfrost-python.svg)](https://pypi.org/project/blockfrost-python/)\n[![License](https://img.shields.io/pypi/l/blockfrost-python.svg)](https://github.com/blockfrost/blockfrost-python/blob/master/LICENSE)\n[![Made by Five Binaries](https://img.shields.io/badge/made%20by-Five%20Binaries-darkviolet.svg)](https://fivebinaries.com/)\n[![Maintained by Mathias Frohlich](https://img.shields.io/badge/maintained%20by-Mathias%20Frohlich-blue.svg)](https://github.com/mathiasfrohlich)\n\n<img src=\"https://blockfrost.io/images/logo.svg\" width=\"250\" align=\"right\" height=\"90\">\n\n# blockfrost-python\n\n<br/>\n\n<p align=\"center\">A Python SDK for Blockfrost.io API.</p>\n<p align=\"center\">\n  <a href=\"#getting-started\">Getting started</a> \u2022\n  <a href=\"#installation\">Installation</a> \u2022\n  <a href=\"#usage\">Usage</a>\n</p>\n<br>\n\n## Getting started\n\nTo use this SDK, you first need login into to [blockfrost.io](https://blockfrost.io) create your project to retrieve\nyour API key.\n\n<img src=\"https://i.imgur.com/smY12ro.png\">\n\n<br/>\n\n## Installation\n\n[![PyPI Latest Release](https://img.shields.io/pypi/v/blockfrost-python.svg)](https://pypi.org/project/blockfrost-python/)\n\n```console\n$ pip install blockfrost-python\n```\n\n<br/>\n\n## Usage\n\nUsing the SDK is pretty straight-forward as you can see from the following examples.\n\n### Cardano\n\n```python\nfrom blockfrost import BlockFrostApi, ApiError, ApiUrls\n\napi = BlockFrostApi(\n    project_id='YOUR API KEY HERE',  # or export environment variable BLOCKFROST_PROJECT_ID\n    # optional: pass base_url or export BLOCKFROST_API_URL to use testnet, defaults to ApiUrls.mainnet.value\n    base_url=ApiUrls.testnet.value,\n)\ntry:\n    health = api.health()\n    print(health)   # prints object:    HealthResponse(is_healthy=True)\n    health = api.health(return_type='json') # Can be useful if python wrapper is behind api version\n    print(health)   # prints json:      {\"is_healthy\":True}\n    health = api.health(return_type='pandas')\n    print(health)   # prints Dataframe:         is_healthy\n                    #                       0         True\n\n\n    account_rewards = api.account_rewards(\n        stake_address='stake1ux3g2c9dx2nhhehyrezyxpkstartcqmu9hk63qgfkccw5rqttygt7',\n        count=20,\n    )\n    print(account_rewards[0].epoch)  # prints 221\n    print(len(account_rewards))  # prints 20\n\n    account_rewards = api.account_rewards(\n        stake_address='stake1ux3g2c9dx2nhhehyrezyxpkstartcqmu9hk63qgfkccw5rqttygt7',\n        count=20,\n        gather_pages=True, # will collect all pages\n    )\n    print(account_rewards[0].epoch)  # prints 221\n    print(len(account_rewards))  # prints 57\n\n    address = api.address(\n        address='addr1qxqs59lphg8g6qndelq8xwqn60ag3aeyfcp33c2kdp46a09re5df3pzwwmyq946axfcejy5n4x0y99wqpgtp2gd0k09qsgy6pz')\n    print(address.type)  # prints 'shelley'\n    for amount in address.amount:\n        print(amount.unit)  # prints 'lovelace'\n\nexcept ApiError as e:\n    print(e)\n```\n\n### IPFS\n\n```python\nfrom blockfrost import BlockFrostIPFS, ApiError\n\nipfs = BlockFrostIPFS(\n    project_id='YOUR API KEY HERE'  # or export environment variable BLOCKFROST_PROJECT_ID\n)\nfile_hash = None\ntry:\n    ipfs_object = ipfs.add('./README.md')\n    file_hash = ipfs_object.ipfs_hash\n    print(file_hash)\nexcept ApiError as e:\n    print(e)\n\ntry:\n    with open('./README_downloaded.md', 'w') as file:\n        file_data = ipfs.gateway(IPFS_path=file_hash).text\n        file.write(file_data)\nexcept ApiError as e:\n    print(e)\n```\n\n### Verifying Secure Webhook signature\n\nWebhooks 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.\nTo learn more about Secure Webhooks, see [Secure Webhooks Docs](https://blockfrost.dev/docs/start-building/webhooks/).\n\nYou can verify the signature using `verifyWebhookSignature` function.\n\nExample:\n\n```python\n# Example of Python Flask app with /webhook endpoint\n# for processing events sent by Blockfrost Secure Webhooks\nfrom flask import Flask, request, json\nfrom blockfrost import verify_webhook_signature, SignatureVerificationError\n\nSECRET_AUTH_TOKEN = \"SECRET-WEBHOOK-AUTH-TOKEN\"\n\napp = Flask(__name__)\n\n@app.route('/webhook', methods=['POST'])\ndef webhook():\n    if request.method == 'POST':\n        # Validate webhook signature\n        request_bytes = request.get_data()\n        try:\n            verify_webhook_signature(\n                request_bytes, request.headers['Blockfrost-Signature'], SECRET_AUTH_TOKEN)\n        except SignatureVerificationError as e:\n            # for easier debugging you can access passed header and request_body values (e.header, e.request_body)\n            print('Webhook signature is invalid.', e)\n            return 'Invalid signature', 403\n\n        # Get the payload as JSON\n        event = request.json\n\n        print('Received request id {}, webhook_id: {}'.format(\n            event['id'], event['webhook_id']))\n\n        if event['type'] == \"block\":\n            # process Block event\n            print('Received block hash {}'.format(event['payload']['hash']))\n        elif event['type'] == \"...\":\n            # truncated\n        else:\n            # Unexpected event type\n            print('Unexpected event type {}'.format(event['type']))\n\n        return 'Webhook received', 200\n    else:\n        return 'POST Method not supported', 405\n\n\n\nif __name__ == \"__main__\":\n    app.run(host='0.0.0.0', port=6666)\n```\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "The official Python SDK for Blockfrost API v0.1.37",
    "version": "0.5.3",
    "split_keywords": [
        "blockfrost",
        "blockchain",
        "cardano",
        "ipfs"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1e13cd5e3c7fa887303cd63401268e3cfea0faa59dac6a82bfce4e2b577a03db",
                "md5": "8ec799193ee73bbddc95629b17fa64ef",
                "sha256": "b0e73f09f1ff06977c85ccd63f6afe7ec30fa1b5c48e94a15d8bc8cf1f61997b"
            },
            "downloads": -1,
            "filename": "blockfrost_python-0.5.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8ec799193ee73bbddc95629b17fa64ef",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7, <4",
            "size": 29058,
            "upload_time": "2023-02-08T10:12:26",
            "upload_time_iso_8601": "2023-02-08T10:12:26.760321Z",
            "url": "https://files.pythonhosted.org/packages/1e/13/cd5e3c7fa887303cd63401268e3cfea0faa59dac6a82bfce4e2b577a03db/blockfrost_python-0.5.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a9606701ac0588ba48dda821a1249aee447ceeb844601d00c509c17843a3af6e",
                "md5": "2141ad50d95ef868da2ab311b81992c2",
                "sha256": "3154b99867e7714c90064c9e1a37e3b7af97c107b64549dd0d424aaa3209017e"
            },
            "downloads": -1,
            "filename": "blockfrost-python-0.5.3.tar.gz",
            "has_sig": false,
            "md5_digest": "2141ad50d95ef868da2ab311b81992c2",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7, <4",
            "size": 37028,
            "upload_time": "2023-02-08T10:12:28",
            "upload_time_iso_8601": "2023-02-08T10:12:28.275748Z",
            "url": "https://files.pythonhosted.org/packages/a9/60/6701ac0588ba48dda821a1249aee447ceeb844601d00c509c17843a3af6e/blockfrost-python-0.5.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-02-08 10:12:28",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "blockfrost",
    "github_project": "blockfrost-python",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [
        {
            "name": "requests",
            "specs": []
        }
    ],
    "lcname": "blockfrost-python"
}
        
Elapsed time: 0.05042s