Перейти к основному контенту

Python: How to perform batch requests with Infura

Below is a short script for showcasing how you can 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.

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, secret, and URL will be needed for passing to the request's 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 three responses for our three 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()
Was this helpful?
Connect MetaMask to provide feedback
What is this?
This is a trial feedback system that uses Verax to record your feedback as onchain attestations on Linea Mainnet. When you vote, submit a transaction in your wallet.