How to Use the HugeGraph Python Client to Interact with HugeGraph: A Complete Developer Guide
The HugeGraph Python client (pyhugegraph) wraps HugeGraph's HTTP API into convenient Python objects, using a lazy-initialization manager pattern to handle schema definition, graph mutations, and Gremlin queries with minimal overhead.
The HugeGraph Python client, maintained in the apache/incubator-hugegraph-ai repository, transforms HugeGraph's REST endpoints into an idiomatic Python interface. This thin wrapper eliminates the need to manually construct HTTP requests while providing automatic authentication, version detection, and graphspace support for HugeGraph 3.0+. Whether you are defining property schemas or executing complex traversals, the client abstracts the underlying REST complexity into type-safe method calls.
Architecture and Core Components
The client follows a lazy-initialization manager pattern that delays HTTP session creation until you actually request a specific operation. Understanding these four core components helps you navigate the source code effectively:
-
PyHugeClient– The central entry point inhugegraph-python-client/src/pyhugegraph/client.pythat stores connection configuration and creates manager objects on demand using the@manager_builderdecorator (lines 37‑45). -
HGraphConfig– Located inhugegraph-python-client/src/pyhugegraph/utils/huge_config.py, this class holds the server URL, credentials, target graph, and optional graphspace. Its__post_init__method (lines 44‑62) automatically queries/versionsto detect server capabilities and enables graphspace support for HugeGraph 3.0+. -
HGraphSession– A thin wrapper aroundrequests.Sessionfound inhugegraph-python-client/src/pyhugegraph/utils/huge_requests.pythat automatically injects authentication headers and timeout settings for every request. -
Manager Classes – Specialized wrappers for REST endpoints including
SchemaManager(schema.py),GraphManager(graph.py),GremlinManager(gremlin.py),GraphsManager(graphs.py), andTaskManager.
Installation and Setup
Install the client from PyPI before connecting to your HugeGraph server:
pip install pyhugegraph
Verify your HugeGraph server is running and accessible at a known URL (default: http://127.0.0.1:8080). You will need valid credentials and the name of an existing graph to connect.
Connecting to HugeGraph
Instantiate PyHugeClient with your server details. The constructor builds an HGraphConfig object and automatically detects your server version to determine available features.
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
As implemented in client.py (lines 49‑60), the client resolves the graphspace parameter in HGraphConfig.__post_init__ based on the server version response.
Schema Management
Use the SchemaManager to define property keys, vertex labels, and edge labels before inserting data. The manager constructs REST payloads and sends them to the /schema endpoint.
schema = client.schema()
# Define property keys
schema.propertyKey("name").asText().ifNotExist().create()
schema.propertyKey("birthDate").asText().ifNotExist().create()
# Create vertex labels with primary keys
schema.vertexLabel("Person") \
.properties("name", "birthDate") \
.usePrimaryKeyId() \
.primaryKeys("name") \
.ifNotExist() \
.create()
schema.vertexLabel("Movie") \
.properties("name") \
.usePrimaryKeyId() \
.primaryKeys("name") \
.ifNotExist() \
.create()
# Define relationships between vertex types
schema.edgeLabel("ActedIn") \
.sourceLabel("Person") \
.targetLabel("Movie") \
.ifNotExist() \
.create()
Each chained method builds a request payload that SchemaManager (defined in hugegraph-python-client/src/pyhugegraph/api/schema.py) validates before transmission.
Graph Data Operations
The GraphManager provides CRUD operations for vertices and edges through the graph() accessor.
graph = client.graph()
# Add vertices
p1 = graph.addVertex("Person", {"name": "Al Pacino", "birthDate": "1940-04-25"})
p2 = graph.addVertex("Person", {"name": "Robert De Niro", "birthDate": "1943-08-17"})
m1 = graph.addVertex("Movie", {"name": "The Godfather"})
m2 = graph.addVertex("Movie", {"name": "The Godfather Part II"})
# Create edges between vertices
graph.addEdge("ActedIn", p1.id, m1.id, {})
graph.addEdge("ActedIn", p1.id, m2.id, {})
graph.addEdge("ActedIn", p2.id, m2.id, {})
# Release resources
graph.close()
Under the hood, GraphManager.addVertex issues POST requests to /graphs/{graph}/vertices and addEdge posts to /graphs/{graph}/edges, as implemented in hugegraph-python-client/src/pyhugegraph/api/graph.py.
Querying with Gremlin
Execute Gremlin traversals through the GremlinManager to retrieve data without writing raw HTTP requests.
gremlin = client.gremlin()
# Find all movies acted by Al Pacino
result = gremlin.gremlin(
"g.V().hasLabel('Person').has('name', 'Al Pacino').out('ActedIn').valueMap()"
)
print(result) # Returns a list of property maps for matched movies
The gremlin() method in hugegraph-python-client/src/pyhugegraph/api/gremlin.py sends the query string to the /gremlin endpoint and parses the JSON response into Python dictionaries.
Administrative Operations
Manage multiple graphs and inspect server health using specialized managers.
Working with Multiple Graphs
graphs = client.graphs()
# Create a new graph with metadata
graphs.createGraph("my_graph", {"description": "Demo graph"})
# Remove a graph
graphs.dropGraph("my_graph")
The GraphsManager class in hugegraph-python-client/src/pyhugegraph/api/graphs.py wraps the administrative /graphs APIs for creating and dropping graph instances.
Checking Server Version
version = client.version()
print("HugeGraph version:", version.get_version())
This queries the /versions endpoint via VersionManager in hugegraph-python-client/src/pyhugegraph/api/version.py to confirm server compatibility.
Summary
- The HugeGraph Python client uses a lazy-initialization pattern where managers like
SchemaManagerandGraphManagerare instantiated only when accessed viaclient.schema()orclient.graph(). - Configuration handling in
HGraphConfigautomatically detects HugeGraph server versions and enables graphspace support for versions 3.0 and above. - Schema definition follows a fluent API pattern where chained method calls build REST payloads for property keys, vertex labels, and edge labels.
- Data manipulation methods such as
addVertex()andaddEdge()inGraphManagerabstract the HTTP POST requests to the vertices and edges endpoints. - Gremlin queries execute through
GremlinManager.gremlin(), returning parsed JSON results without manual HTTP handling.
Frequently Asked Questions
How do I install and configure the HugeGraph Python client?
Install the package using pip install pyhugegraph. To configure the client, instantiate PyHugeClient with your server URL, credentials, graph name, and optional graphspace. The client automatically detects your HugeGraph version via the /versions endpoint and adjusts capabilities accordingly, as implemented in HGraphConfig.__post_init__.
What is the difference between graph and graphspace in the client configuration?
The graph parameter specifies the target graph database name, while graphspace (defaulting to "DEFAULT" for HugeGraph 3.0+) provides a namespace for multi-tenant deployments. According to the source code in hugegraph-python-client/src/pyhugegraph/utils/huge_config.py, the client automatically sets the graphspace based on version detection if not explicitly provided.
How does the client handle authentication and session management?
The HGraphSession class in hugegraph-python-client/src/pyhugegraph/utils/huge_requests.py wraps requests.Session and automatically injects authentication headers and timeout settings into every HTTP request. When you create a PyHugeClient, it initializes this session wrapper with your provided credentials, ensuring all subsequent API calls include proper authentication without manual header manipulation.
Can I use the HugeGraph Python client with server versions older than 3.0?
Yes, the client maintains backward compatibility. The HGraphConfig class detects the server version during initialization and disables graphspace features for older servers. However, you should verify that specific manager methods you intend to use exist in your server's REST API version, as newer endpoints may not be available on legacy deployments.
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 →