2

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')}`}
})
Vic Rokx
  • 77
  • 1
  • 7

2 Answers2

2

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

  • Firstly thanks so much for your answer. Secondly for the s.header.update({..... what do I put here for the dictionary username and password....}), because printing s.headers, does not really give me insight on what dictionary keys I should use. – Vic Rokx May 11 '21 at 11:34
  • 1
    I had indeed the same question, got it resolved here: https://stackoverflow.com/questions/67461924/how-to-provide-credentials-to-ankr-when-calling-the-api-with-web3-js-httpprovide/67462048 I hope this helps :) – Fernando Jesus Garcia Hipola May 13 '21 at 08:07
2

I found the method below worked well when connecting to the "Basic authentication" method which required a username and password.

Alternatively, using the "Token" method did not require a username and password and that also successfully gives you an Ankr API endpoint.

from web3 import Web3
import requests
import base64

ankr_eth_url = 'INSERT_ANKR_API_ENDPOINT'
s = requests.Session()

# Make sure to use the Project Username and not your log-in username
# myProjectUsername:password
upass = "myProjectUsername:12345678".encode("ascii")
b64 = base64.b64encode(upass).decode("ascii")

s.headers.update({'Authorization': 'Basic ' + b64})

w3 = Web3(Web3.HTTPProvider(ankr_eth_url, session=s))
print(w3.isConnected())
JojoBee
  • 21
  • 1