The communication service providing interface is key to how Web3 interacts with blockchain. The interface accepts the JSON-RPC request and returns the response. This is typically done by submitting the request to a server based on HTTP or IPC sockets.

If you’re already happily connected to your Ethereum node, then you can skip this section.

Choose how to connect to your node

Most nodes have multiple connections. If you are not sure which node to use, go to How to choose which node to use?

The most common way to connect nodes is:

  • 1.IPC (Using local file system: fastest, most secure)
  • Websockets (Remote working, faster than HTTP)
  • 3.HTTP (more nodes support it)

If you are not sure how to decide, please choose the following methods:

  • If you have the option of running web3.py on the same computer as the node, select IPC.
  • If you must connect to nodes on other computers, use Websockets.
  • If your node does not support Websockets, use HTTP.

Most nodes have a way to “close” the connection option. We recommend that you turn off all unused connection options. This provides a more secure setup: it reduces the number of ways that malicious hackers can try to steal your Ether.

Once the connection is determined, you can specify the details using the Communication Service Provider. The communication service Provider is a Web3.py class configured for the desired type of connection.

Look at these:

  • IPCProvider
  • WebsocketProvider
  • HTTPProvider

After configuring the communication service interface program, as follows:

from web3 import Web3
my_provider = Web3.IPCProvider('/my/node/ipc/path')
Copy the code

You can then initialize the Web3 instance as follows:

w3 = Web3(my_provider)
Copy the code

In this way, you are ready to start using Web3.py.

Automatic and manual communication services provide interfaces

If the communication service provider interface program is not specified, the Web3 object looks for ethereum nodes in several standard locations. Automatic detection occurs during initialization:

from web3.auto import w3

# which is equivalent to:

from web3 import Web3
w3 = Web3()
Copy the code

Sometimes, Web3 cannot automatically detect the location of a node.

  • If you are unsure which connection method to use, see above.
  • If you know how to connect, but do not know other information needed to connect (such as the path to the IPC file), you need to look for that information in the configuration of the node.
  • If you are not sure which node to use, see How to Select nodes to Use? .

For a deeper understanding of how automatic detection works, follow:

How does automatic detection work

Web3 attempts to connect to nodes in the following order, with the first successful connection it can make:

  • The connection specified by the environment variable.
  • IPCProvider, which looks for several IPC file locations.
  • HTTPProvider, trying to connect tohttp://localhost:8545.
  • If no provider succeeds, you can still use the Web3 API that does not require a connection, for example:
    • Type Conversions.
    • Currency Conversions.
    • Addresses are related.
    • Use the Local Private key.
    • And so on.

Examples using automatic detection

Some nodes provide apis that go beyond the standard. Sometimes the same information is provided in different ways across nodes. If you’re writing code that works across multiple nodes, you might want to look up the type of node you’re connected to.

For example, the following retrieves geth and Parity client Enode endpoints:

from web3.auto import w3

connected = w3.isConnected()

if connected and w3.version.node.startswith('Parity'):
    enode = w3.parity.enode

elif connected and w3.version.node.startswith('Geth'):
    enode = w3.admin.nodeInfo['enode']

else:
    enode = None
Copy the code

By environment variables

Alternatively, you can set the environment variable WEB3_PROVIDER_URI before launching the script, and Web3 will look for this approach first.

The valid format for this environment variable is:

  • file:///path/to/node/rpc-json/file.ipc
  • http://192.168.1.2:8545
  • https://node.ontheweb.com
  • Ws: / / 127.0.0.1:8546

Shortcut for automatic initialization

There are several shortcuts to automatic initialization in common methods.

Infura Mainnet

To easily connect to Infura Mainnet remote nodes, register first if you don’t have infura. IO /signup…

Then use your API key to set the environment variable INFURA_API_KEY:

$ export INFURA_API_KEY=YourApiKey
Copy the code
>>> from web3.auto.infura import w3

# confirm that the connection succeeded
>>> w3.isConnected()
True
Copy the code

Geth dev PoA

To connect to geth –dev PoA(proof-of-authority) instance with default values:

>>> from web3.auto.gethdev import w3

# confirm that the connection succeeded
>>> w3.isConnected()
True
Copy the code

Built-in communication services provide interfaces

Web3 comes with the following communication service provider interface programs for connecting to local and remote JSON-RPC servers.

HTTPProvider

 class web3.providers.rpc.HTTPProvider(endpoint_uri[, request_kwargs])
Copy the code

This communication service provides an interface program that handles the interaction with a JSON-RPC server based on HTTP or HTTPS.

  • endpoint_uriShould be the full URI of the RPC endpoint, for example'https://localhost:8545'. For HTTP connections running on port 80 followed by RPC servers and HTTPS connections running on port 443, this port can be omitted from the URI.
  • request_kwargsThis should be the dictionary of keyword arguments that will be passed to the HTTP/HTTPS request.
>>> from web3 import Web3
>>> web3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545"))
Copy the code

Note that only one HTTPProvider should be created per Python process, because HTTPProvider reclaims the underlying TCP/IP network connection for better performance.

HTTPProvider uses the Python request library to make requests. If you want to change the way requests are made, you can use request_kwargs to do so. A common use case is to increase the timeout per request.

>>> from web3 import Web3
>>> web3 = Web3(Web3.HTTPProvider("http://127.0.0.1:8545", request_kwargs={'timeout': 60}))
Copy the code

IPCProvider

web3.providers.ipc.IPCProvider(ipc_path=None, testnet=False, timeout=10)
Copy the code

This communication service provides an interface program to handle the interaction with a JSON-RPC server based on IPC sockets.

  • ipc_pathIs the file system path of the IPC socket. : 56
>>> from web3 import Web3
>>> web3 = Web3(Web3.IPCProvider("~/Library/Ethereum/geth.ipc"))
Copy the code

If ipC_path is not specified, it will use the first IPC file it can find from the following table:

  • On Linux and FreeBSD:
  • ~/.ethereum/geth.ipc
  • ~/.local/share/io.parity.ethereum/jsonrpc.ipc
  • On Mac OS:
  • ~/Library/Ethereum/geth.ipc
  • ~/Library/Application Support/io.parity.ethereum/jsonrpc.ipc
  • On Windows:
  • \.\pipe\geth.ipc
  • \.\pipe\jsonrpc.ipc

WebsocketProvider

 class web3.providers.websocket.WebsocketProvider(endpoint_uri[, websocket_kwargs])
Copy the code

This communication service provides an interface program to handle interactions with a WS or WSS based JSON-RPC server.

  • endpoint_uriShould be the full URI of the RPC endpoint, for examplews://localhost:8546.
  • websocket_kwargsShould be the dictionary of keyword arguments that will be passed tows/wss websocketThe connection.
>>> from web3 import Web3
>>> web3 = Web3(Web3.WebsocketProvider(Ws: / / 127.0.0.1:8546 ""))
Copy the code

The WebsocketProvider uses the Python WebSockets library to make requests. If you want to modify the way requests are made, you can do so using websocket_kwargs. A common use case is to increase the timeout per request.

>>> from web3 import Web3
>>> web3 = Web3(Web3.WebsocketProvider("http://127.0.0.1:8546", websocket_kwargs={'timeout': 60}))Copy the code