How to Connect the HugeGraph Python Client to a Running HugeGraph Instance
To connect the HugeGraph Python client to a running HugeGraph instance, instantiate PyHugeClient with your server URL, credentials, and target graph name; the client automatically configures the HTTP session, resolves the server version, and lazily initializes manager classes for schema, graph, and Gremlin operations.
The HugeGraph Python client (pyhugegraph) from the apache/incubator-hugegraph-ai repository provides a Pythonic wrapper around HugeGraph's REST API. It implements a lazy-initialization manager pattern that creates HTTP sessions and API endpoints only when accessed, ensuring efficient resource usage while maintaining a simple, intuitive interface.
Architecture and Connection Components
Understanding how the client manages connections helps troubleshoot issues and optimize usage. The architecture consists of four primary components that work together to translate Python method calls into REST API requests.
PyHugeClient: The Central Entry Point
The PyHugeClient class in hugegraph-python-client/src/pyhugegraph/client.py serves as the main interface. When instantiated, it creates an HGraphConfig object and prepares manager classes that are built on-demand using the manager_builder decorator (lines 37-45). This decorator caches manager instances after first access, preventing unnecessary session creation.
HGraphConfig: Connection Configuration
Located in hugegraph-python-client/src/pyhugegraph/utils/huge_config.py, this class stores connection parameters including the server URL, authentication credentials, target graph name, and optional graphspace. The __post_init__ method (lines 44-62) automatically queries the server version via /versions and enables graphspace support for HugeGraph versions 3.0 and above, defaulting to "DEFAULT" when not specified.
HGraphSession: HTTP Request Management
The HGraphSession class in hugegraph-python-client/src/pyhugegraph/utils/huge_requests.py extends requests.Session to inject authentication headers and timeout settings into every request. This ensures consistent authentication handling without manual header management.
Manager Classes: API Abstractions
Specific managers handle different API domains:
- SchemaManager (
api/schema.py): Handles property keys, vertex labels, and edge labels - GraphManager (
api/graph.py): Manages vertices and edges - GremlinManager (
api/gremlin.py): Executes Gremlin queries
Step-by-Step Connection Guide
Installation
Install the client from PyPI before establishing a connection:
pip install pyhugegraph
Basic Connection Setup
Import PyHugeClient and instantiate it with your server details. The constructor accepts the URL, username, password, graph name, and optional graphspace:
from pyhugegraph.client import PyHugeClient
client = PyHugeClient(
url="http://127.0.0.1:8080",
user="admin",
pwd="admin",
graph="hugegraph",
graphspace=None, # Optional: defaults to "DEFAULT" for v3+
)
print(client) # Displays resolved configuration including detected version
The PyHugeClient.__init__ method (lines 49-60 in client.py) builds the HGraphConfig object, while HGraphConfig.__post_init__ validates connectivity and determines API capabilities.
Verifying Server Connectivity
After instantiation, verify the connection by checking the server version:
version = client.version()
print("HugeGraph version:", version.get_version())
This invokes VersionManager to query the /versions endpoint, confirming that authentication and networking are properly configured.
Working with Manager Classes After Connection
Once connected, access specific functionality through manager properties. These are lazily instantiated on first access and cached for reuse.
Schema Management
Access the schema manager to define property keys, vertex labels, and edge labels:
schema = client.schema()
# Create property keys
schema.propertyKey("name").asText().ifNotExist().create()
schema.propertyKey("birthDate").asText().ifNotExist().create()
# Define vertex labels
schema.vertexLabel("Person") \
.properties("name", "birthDate") \
.usePrimaryKeyId() \
.primaryKeys("name") \
.ifNotExist() \
.create()
The schema() method uses the manager_builder decorator to instantiate SchemaManager only when first called.
Graph Operations (Vertices and Edges)
Use the graph manager to add and modify data:
graph = client.graph()
# Add vertices
p1 = graph.addVertex("Person", {"name": "Al Pacino", "birthDate": "1940-04-25"})
m1 = graph.addVertex("Movie", {"name": "The Godfather"})
# Create edges
graph.addEdge("ActedIn", p1.id, m1.id, {})
graph.close()
GraphManager.addVertex issues POST /graphs/{graph}/vertices, while addEdge targets /graphs/{graph}/edges.
Gremlin Query Execution
Execute traversals against the connected graph:
gremlin = client.gremlin()
result = gremlin.gremlin(
"g.V().hasLabel('Person').has('name', 'Al Pacino').out('ActedIn').valueMap()"
)
print(result)
Complete Working Example
The following runnable script demonstrates end-to-end connection and usage, adapted from hugegraph-python-client/src/pyhugegraph/example/hugegraph_example.py:
from pyhugegraph.client import PyHugeClient
def main():
# 1. Connect to the HugeGraph instance
client = PyHugeClient(
url="http://127.0.0.1:8080",
user="admin",
pwd="admin",
graph="hugegraph"
)
# 2. Verify connection
print(f"Server version: {client.version().get_version()}")
# 3. Define schema
schema = client.schema()
schema.propertyKey("name").asText().ifNotExist().create()
schema.vertexLabel("Person").properties("name").usePrimaryKeyId().primaryKeys("name").ifNotExist().create()
# 4. Insert data
graph = client.graph()
vertex = graph.addVertex("Person", {"name": "Alice"})
print(f"Created vertex: {vertex.id}")
# 5. Query using Gremlin
gremlin = client.gremlin()
result = gremlin.gremlin("g.V().hasLabel('Person').count()")
print(f"Total persons: {result}")
if __name__ == "__main__":
main()
Summary
- Instantiate
PyHugeClientwithurl,user,pwd, andgraphparameters to establish a connection to your HugeGraph instance. - Automatic configuration occurs via
HGraphConfig.__post_init__, which detects server versions and configures graphspace support for HugeGraph 3.0+. - Lazy initialization through the
manager_builderdecorator ensures managers likeSchemaManagerandGraphManagerare created only when accessed viaclient.schema(),client.graph(), orclient.gremlin(). - HTTP session management is handled transparently by
HGraphSession, which injects authentication headers and handles request timeouts. - Source files implementing this logic include
client.py,huge_config.py, andhuge_requests.pyin theapache/incubator-hugegraph-airepository.
Frequently Asked Questions
What authentication methods does the HugeGraph Python client support?
The client supports basic HTTP authentication via username and password parameters passed to PyHugeClient. The HGraphSession class automatically encodes these credentials into the Authorization header for every request. Token-based authentication and SSL/TLS configuration can be handled by modifying the HGraphSession or passing additional parameters to the underlying requests.Session object.
How do I connect to a specific graphspace in HugeGraph 3.0?
Pass the graphspace parameter when instantiating PyHugeClient. For HugeGraph versions 3.0 and above, the HGraphConfig.__post_init__ method automatically detects version compatibility and defaults to the "DEFAULT" graphspace if none is specified. If connecting to HugeGraph 2.x or earlier, the graphspace parameter is ignored.
Why is my connection failing with timeout errors?
The HGraphSession wraps Python's requests library and uses default timeout settings. Connection timeouts typically indicate network issues, incorrect URL formatting, or the HugeGraph server not running. Verify the server is accessible at the /versions endpoint using a standard HTTP client before troubleshooting the Python client configuration.
Can I connect to multiple HugeGraph instances simultaneously?
Yes. Instantiate multiple PyHugeClient objects with different connection parameters. Each instance maintains its own HGraphConfig and manager cache, allowing you to interact with different servers or different graphs on the same server within the same Python process without session conflicts.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →