Package: blockfrost-python
blockfrost-pythonA Python SDK for Blockfrost.io API.Getting started•Installation•UsageGetting startedTo use this SDK, you first need login into toblockfrost.iocreate your project to retrieve
your API key.Installation$pipinstallblockfrost-pythonUsageUsing the SDK is pretty straight-forward as you can see from the following examples.CardanofromblockfrostimportBlockFrostApi,ApiError,ApiUrlsapi=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.valuebase_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 versionprint(health)# prints json:      {"is_healthy":True}health=api.health(return_type='pandas')print(health)# prints Dataframe:         is_healthy#                       0         Trueaccount_rewards=api.account_rewards(stake_address='stake1ux3g2c9dx2nhhehyrezyxpkstartcqmu9hk63qgfkccw5rqttygt7',count=20,)print(account_rewards[0].epoch)# prints 221print(len(account_rewards))# prints 20account_rewards=api.account_rewards(stake_address='stake1ux3g2c9dx2nhhehyrezyxpkstartcqmu9hk63qgfkccw5rqttygt7',count=20,gather_pages=True,# will collect all pages)print(account_rewards[0].epoch)# prints 221print(len(account_rewards))# prints 57address=api.address(address='addr1qxqs59lphg8g6qndelq8xwqn60ag3aeyfcp33c2kdp46a09re5df3pzwwmyq946axfcejy5n4x0y99wqpgtp2gd0k09qsgy6pz')print(address.type)# prints 'shelley'foramountinaddress.amount:print(amount.unit)# prints 'lovelace'exceptApiErrorase:print(e)IPFSfromblockfrostimportBlockFrostIPFS,ApiErroripfs=BlockFrostIPFS(project_id='YOUR API KEY HERE'# or export environment variable BLOCKFROST_PROJECT_ID)file_hash=Nonetry:ipfs_object=ipfs.add('./README.md')file_hash=ipfs_object.ipfs_hashprint(file_hash)exceptApiErrorase:print(e)try:withopen('./README_downloaded.md','w')asfile:file_data=ipfs.gateway(IPFS_path=file_hash).textfile.write(file_data)exceptApiErrorase:print(e)Verifying Secure Webhook signatureWebhooks 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'sBlockfrost-Signatureheader. This allows you to verify that the events were sent by Blockfrost, not by a third party.
To learn more about Secure Webhooks, seeSecure Webhooks Docs.You can verify the signature usingverifyWebhookSignaturefunction.Example:# Example of Python Flask app with /webhook endpoint# for processing events sent by Blockfrost Secure WebhooksfromflaskimportFlask,request,jsonfromblockfrostimportverify_webhook_signature,SignatureVerificationErrorSECRET_AUTH_TOKEN="SECRET-WEBHOOK-AUTH-TOKEN"app=Flask(__name__)@app.route('/webhook',methods=['POST'])defwebhook():ifrequest.method=='POST':# Validate webhook signaturerequest_bytes=request.get_data()try:verify_webhook_signature(request_bytes,request.headers['Blockfrost-Signature'],SECRET_AUTH_TOKEN)exceptSignatureVerificationErrorase:# 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 JSONevent=request.jsonprint('Received request id{}, webhook_id:{}'.format(event['id'],event['webhook_id']))ifevent['type']=="block":# process Block eventprint('Received block hash{}'.format(event['payload']['hash']))elifevent['type']=="...":# truncatedelse:# Unexpected event typeprint('Unexpected event type{}'.format(event['type']))return'Webhook received',200else:return'POST Method not supported',405if__name__=="__main__":app.run(host='0.0.0.0',port=6666)