Nhảy tới nội dung

Python: How to perform batch requests with Infura

Hello everyone 🤙!

Below is a short script I wrote for showcasing how one could perform batch requests (multiple requests at once) using Python and Infura. Feel free to scroll down to the end of the article if you’re interested solely in the code of the script.

Prerequisites

The only requirement for running this script is having the ‘requests’ library installed. This library makes it really easy and convenient to perform HTTP requests in our python code.

To install the library on Linux or MacOS, simply run the command below:

pip install requests

Building the script

First of all, let’s import the requests library and set up the variables needed for connecting to Infura:

import requests

api_key = '229f0...'
infura_url = 'https://mainnet.infura.io/v3/229f0...'

The project’s id and secret, along with the URL will be needed for passing through to the requests POST method, for authentication.

Next, we need to build our requests list. This is going to be a list of JSON objects, and for the sake of this tutorial we’ll be calling eth_blockNumber.

requests_json = [
{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []},
{"jsonrpc": "2.0", "id": 2, "method": "eth_blockNumber", "params": []},
{"jsonrpc": "2.0", "id": 3, "method": "eth_blockNumber", "params": []}
]

Finally, for performing the actual request let’s create a method called batch(), where the requests library can do its magic.

def batch():
response = requests.post(url=infura_url, json=requests_json, auth=(api_key))
if response.status_code == 200:
res = response.json()
for i in res:
print(i['result'])

Since the response is a list of 3 responses for our 3 requests, we’ll need to go through each of them by using the for loop at the end of the method.

Complete code overview

import requests

api_key = '229f0...'
infura_url = 'https://mainnet.infura.io/v3/229f0...'

requests_json = [
{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []},
{"jsonrpc": "2.0", "id": 2, "method": "eth_blockNumber", "params": []},
{"jsonrpc": "2.0", "id": 3, "method": "eth_blockNumber", "params": []}
]

def batch():
response = requests.post(url=infura_url, json=requests_json, auth=(api_key))
if response.status_code == 200:
res = response.json()
for i in res:
print(i['result'])

if __name__ == "__main__":
batch()

Congratulations, you now know how to perform batch requests with Python and Infura! 🥂