Search code examples
python-3.xweb3py

Python Web3 connect to Ankr Binance Smart Chain API, through user and password


Maybe this is a dumb question but for web3.js there is the option to use another API service Ankr, instead of Infura. Ankr gives access to BSC network which has lower fees. I cannot seem to figure out how to connect to Ankr through python web3 as it requires authentication with a username and password. It returns false when I run the python code. I am not sure which keys I am suppose to use for web3.py, or possibly the syntax for the call is wrong, when I use the requests library everything works fine so it is not an issue with the address.

# Python Code Unsuccessful 
Ankr_bsc_url = 'https............' 
web3 = Web3(Web3.HTTPProvider(Ankr_bsc_url, request_kwargs={'headers': {'Username': user, 'Password': password}}))

print(web3.isConnected())



//Node.js Code web3.js Works
const web3Provider = new Web3.providers.WebsocketProvider(url, {
 headers: { authorization: `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`}
})

Solution

  • You should save the headers on a Session object, and pass it as a parameter of HTTPProvider

    from web3 import Web3
    import requests
    
    s = requests.Session()
    s.headers.update({'authorization': 'Basic ZZZZ'})
    
    # HTTPProvider:
    w3 = Web3(Web3.HTTPProvider('https://apis.ankr.com/XXXX/YYYY/binance/full/main', session=s))
    w3.isConnected()
    

    In my case w3.isConnected return True