Ir diretamente para o conteúdo principal

Making Sui gRPC Requests with Python

Atualizado em
Aug 07, 2026

Visão geral

Python is a versatile and widely-used programming language, known for its simplicity and strong community support. This document provides a step-by-step process for setting up a Python environment to interact with Sui gRPC, including project setup, dependency management, and implementing authentication mechanisms.

Authentication Required for Python

To establish a connection with the Sui gRPC server, first initialize a secure gRPC channel by providing the server's endpoint, including the necessary port (9000), and an authentication token. This setup ensures that the connection is both encrypted and authenticated, allowing the client to communicate securely with the server for executing remote procedure calls (RPCs).

def create_sui_grpc_client(endpoint: str, token: str):
# Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token
# For eg: QN Endpoint: https://docs-demo.sui-mainnet.quiknode.pro/abcde123456789
# endpoint will be: docs-demo.sui-mainnet.quiknode.pro:9000 {9000 is the port number for Sui gRPC}
# token will be: abcde123456789

# Create secure SSL channel
channel = grpc.secure_channel(endpoint, grpc.ssl_channel_credentials())

# Create service stub for Ledger operations
stub = ledger_service_pb2_grpc.LedgerServiceStub(channel)

# Prepare authentication metadata with token
metadata = [("x-token", token)]

return stub, metadata

You can call the above function like this:

endpoint = 'docs-demo.sui-mainnet.quiknode.pro:9000'
token = 'abcde123456789'
stub, metadata = create_sui_grpc_client(endpoint, token)

Initiating the Python Project for Sui gRPC

Passo 1: Criar um novo diretório de projeto

Create a dedicated directory for your Sui gRPC project and navigate into it:

mkdir sui-grpc
cd sui-grpc

Create and activate a Python virtual environment to isolate dependencies:

python -m venv venv

# Activate on macOS/Linux
source venv/bin/activate

# Activate on Windows
venv\Scripts\activate

Passo 3: Instalar as dependências gRPC do Protobuf

Ensure you have Python (3.8+) and protoc installed on your machine. Install the core gRPC and Protocol Buffer libraries:

pip install grpcio grpcio-tools protobuf

Passo 4: Organizar o diretório do projeto

Criar um protos folder to store the original Protocol Buffer definition files:

mkdir protos

Download the official Sui proto files from the MystenLabs/sui repository. Extract and place the entire sui directory structure into your newly created protos folder.

A estrutura do seu projeto deve ser a seguinte:

sui-grpc/
├── protos/
│ └── sui/
│ └── rpc/
│ └── v2/
│ ├── ledger_service.proto
│ ├── object.proto
│ ├── transaction.proto
│ └── ... (other proto files)

Step 5: Generate Python Code from Proto Files

Once your folder structure matches the above layout, generate the *_pb2_grpc.py e *_pb2.py files by running the following command:

python -m grpc_tools.protoc \
-I./protos/proto \
--python_out=. \
--grpc_python_out=. \
./protos/proto/sui/rpc/v2/*.proto \
./protos/proto/google/rpc/*.proto \
./protos/proto/google/protobuf/*.proto

It will generate all the required files for running the python examples for Sui gRPC.

Step 6: Create a Client.py File

Set up a main python file for implementing client or server logic:

touch client.py

You can copy and paste the following sample code into your client.py file to get started. The example demonstrates how to interact with the Sui gRPC service to fetch object information.

import grpc
import json
from google.protobuf.field_mask_pb2 import FieldMask
from google.protobuf.json_format import MessageToDict
from sui.rpc.v2 import ledger_service_pb2, ledger_service_pb2_grpc


def get_object():

# Quicknode endpoints consist of two crucial components: the endpoint name and the corresponding token
# For eg: QN Endpoint: https://docs-demo.sui-mainnet.quiknode.pro/abcde123456789
# endpoint will be: docs-demo.sui-mainnet.quiknode.pro:9000 {9000 is the port number for Sui gRPC}
# token will be : abcde123456789

endpoint = 'docs-demo.sui-mainnet.quiknode.pro:9000';
token = 'abcde123456789';

channel = grpc.secure_channel(endpoint, grpc.ssl_channel_credentials())
stub = ledger_service_pb2_grpc.LedgerServiceStub(channel)

# Specify the object ID you want to retrieve
# Replace with an actual Sui object ID
object_id = "0x27c4fdb3b846aa3ae4a65ef5127a309aa3c1f466671471a806d8912a18b253e8"

# Create a field mask to specify which fields to include in the response
read_mask = FieldMask(paths=[
"bcs",
"object_id",
"version",
"digest",
"owner",
"object_type",
"has_public_transfer",
"contents",
"previous_transaction",
"storage_rebate"
])

# Prepare the GetObjectRequest
request = ledger_service_pb2.GetObjectRequest(
object_id=object_id,
read_mask=read_mask
)

metadata = [("x-token", token)]

return stub.GetObject(request, metadata=metadata)


def parse_response_to_json(response):
return json.dumps(
MessageToDict(response, preserving_proto_field_name=True),
indent=2
)


def main():
try:
response = get_object()
print(parse_response_to_json(response))
except grpc.RpcError as e:
print(f"{e.code().name}: {e.details()}")


if __name__ == "__main__":
main()

Step 7: Run Your Code

Antes de executar o seu código, limpe o ambiente e certifique-se de que todas as dependências estão corretamente resolvidas:

python client.py