Skip to content

Commit 4386c19

Browse files
jfrench9claude
andauthored
feat: Add table ingestion API and refactor response handling (#19)
## Summary This PR introduces comprehensive table ingestion capabilities to the robosystems client and performs a major refactor of API response handling across all endpoints. The changes include new table management APIs, removal of deprecated copy functionality, and standardization of response handling patterns. ## Key Accomplishments ### New Table Ingestion Features - **Complete table management API**: Added endpoints for table ingestion, file management, querying, and metadata operations - **File upload/download workflow**: Implemented secure file upload URLs, file info retrieval, and file lifecycle management - **Table querying capabilities**: Added dedicated table query endpoint with enhanced filtering and processing options - **Metadata and listing operations**: Full CRUD operations for table management including listing, updating, and deletion ### API Client Improvements - **Standardized response handling**: Refactored response processing across 100+ API endpoints for consistency - **Enhanced error handling**: Improved error responses and validation across all API modules - **Code organization**: Reorganized API structure by moving from copy-based to table-based data operations - **Documentation updates**: Updated endpoint documentation and parameter specifications ### Deprecated Features Removed - **Legacy copy API**: Removed `copy_data_to_graph.py` in favor of new table ingestion workflow - **Outdated schema operations**: Consolidated and renamed schema-related endpoints for better clarity ## Breaking Changes - **API endpoint changes**: The `/copy/` endpoint has been replaced with `/tables/` endpoints - **Schema endpoint rename**: `get_graph_schema_info.py` renamed to `get_graph_schema.py` - **Response format standardization**: Some response formats may have changed due to standardization efforts ## Testing Notes - All existing API endpoints have been updated with improved response handling - New table ingestion endpoints require testing with various file formats and sizes - Verify that schema operations work correctly after endpoint reorganization - Test file upload/download workflows end-to-end - Validate backward compatibility for non-breaking endpoint changes ## Infrastructure Considerations - The table ingestion feature may require additional storage and processing resources - File upload capabilities introduce new security considerations for file validation and storage - Monitor API performance with the new response handling patterns - Consider rate limiting for file upload operations - Ensure proper cleanup of uploaded files and temporary resources This refactor significantly improves the client's capabilities while maintaining a cleaner, more maintainable codebase structure. --- 🤖 Generated with [Claude Code](https://claude.ai/code) **Branch Info:** - Source: `feature/table-ingest` - Target: `main` - Type: feature Co-Authored-By: Claude <noreply@anthropic.com>
2 parents a8cd1ee + 8bfc265 commit 4386c19

148 files changed

Lines changed: 5451 additions & 2708 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎README.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,18 @@ Official Python Client for the RoboSystems Financial Knowledge Graph API. Access
1616
## Installation
1717

1818
```bash
19+
# Basic installation
1920
pip install robosystems-client
21+
22+
# With table ingestion support (for uploading Parquet files)
23+
pip install robosystems-client[tables]
24+
25+
# All optional features
26+
pip install robosystems-client[all]
2027
```
2128

29+
See the [examples](./examples) directory for usage guides.
30+
2231
## API Reference
2332

2433
- API reference: [https://api.robosystems.ai](https://api.robosystems.ai)

‎examples/README.md‎

Lines changed: 272 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,272 @@
1+
# RoboSystems Python Client Examples
2+
3+
This directory contains examples demonstrating how to use the RoboSystems Python Client SDK for various common workflows.
4+
5+
## Prerequisites
6+
7+
```bash
8+
# Basic installation (for querying only)
9+
pip install robosystems-client
10+
11+
# With table ingestion support (for uploading Parquet files)
12+
pip install robosystems-client[tables]
13+
14+
# Or install all optional features
15+
pip install robosystems-client[all]
16+
```
17+
18+
## Examples
19+
20+
### 1. Basic Query (`basic_query.py`)
21+
22+
**Demonstrates:** Simple querying of an existing graph
23+
24+
The simplest way to get started with the RoboSystems Python SDK. This example shows how to:
25+
- Initialize the SDK with an API key
26+
- Execute Cypher queries against a graph
27+
- Display query results
28+
29+
**Usage:**
30+
```bash
31+
python examples/basic_query.py \
32+
--api-key YOUR_API_KEY \
33+
--graph-id YOUR_GRAPH_ID \
34+
--base-url http://localhost:8000
35+
```
36+
37+
**Key Features:**
38+
- Minimal setup
39+
- Multiple query examples (count nodes, list labels, sample data)
40+
- Proper error handling
41+
- Clean resource management
42+
43+
---
44+
45+
### 2. End-to-End Workflow (`e2e_workflow.py`)
46+
47+
**Demonstrates:** Complete workflow from user creation to querying
48+
49+
This comprehensive example shows the full RoboSystems workflow:
50+
- User creation and authentication
51+
- API key generation
52+
- Graph creation
53+
- Parquet file upload to staging tables
54+
- Table ingestion into the graph
55+
- Querying the populated graph
56+
57+
**Usage:**
58+
59+
**With new user creation:**
60+
```bash
61+
python examples/e2e_workflow.py
62+
```
63+
This will auto-generate credentials and walk through the entire setup.
64+
65+
**With existing API key:**
66+
```bash
67+
python examples/e2e_workflow.py --api-key YOUR_API_KEY
68+
```
69+
70+
**Custom configuration:**
71+
```bash
72+
python examples/e2e_workflow.py \
73+
--name "John Doe" \
74+
--email "john@example.com" \
75+
--password "YourSecurePassword123!" \
76+
--base-url http://localhost:8000
77+
```
78+
79+
**Key Features:**
80+
- Automated user setup
81+
- Sample data generation (creates Parquet files)
82+
- **TableIngestClient** extension usage for simplified uploads
83+
- Progress callbacks
84+
- LocalStack URL auto-fix for local development
85+
- Multiple query examples
86+
87+
---
88+
89+
## Extension Features Demonstrated
90+
91+
### TableIngestClient
92+
93+
The examples showcase the new `TableIngestClient` extension which dramatically simplifies the table upload process:
94+
95+
**Before (Raw API calls - 3 steps):**
96+
```python
97+
# Step 1: Get presigned upload URL
98+
response = client.post(f"{base_url}/v1/graphs/{graph_id}/tables/{table_name}/files", ...)
99+
upload_url = response.json()["upload_url"]
100+
file_id = response.json()["file_id"]
101+
102+
# Step 2: Upload to S3
103+
with open(file_path, "rb") as f:
104+
s3_client.put(upload_url, data=f.read())
105+
106+
# Step 3: Update file metadata
107+
client.patch(f"{base_url}/v1/graphs/{graph_id}/tables/files/{file_id}", ...)
108+
```
109+
110+
**After (SDK with TableIngestClient):**
111+
```python
112+
from robosystems_client.extensions import UploadOptions
113+
114+
# All 3 steps in one call!
115+
upload_result = extensions.tables.upload_parquet_file(
116+
graph_id,
117+
table_name,
118+
file_path,
119+
UploadOptions(on_progress=lambda msg: print(msg))
120+
)
121+
```
122+
123+
**Additional TableIngestClient Methods:**
124+
- `list_staging_tables(graph_id)` - List all staging tables
125+
- `ingest_all_tables(graph_id, options)` - Ingest tables into graph
126+
- `upload_and_ingest(graph_id, table_name, file_path, ...)` - Upload + ingest in one call
127+
128+
---
129+
130+
## Common Patterns
131+
132+
### Initializing the SDK
133+
134+
```python
135+
from robosystems_client.extensions import (
136+
RoboSystemsExtensions,
137+
RoboSystemsExtensionConfig,
138+
)
139+
140+
# With API key
141+
config = RoboSystemsExtensionConfig(
142+
base_url="http://localhost:8000",
143+
headers={"X-API-Key": "your-api-key"}
144+
)
145+
extensions = RoboSystemsExtensions(config)
146+
147+
# Always close when done
148+
extensions.close()
149+
```
150+
151+
### Uploading Data
152+
153+
```python
154+
from robosystems_client.extensions import UploadOptions, IngestOptions
155+
from pathlib import Path
156+
157+
# Upload a parquet file
158+
upload_options = UploadOptions(
159+
on_progress=lambda msg: print(f"Upload: {msg}"),
160+
fix_localstack_url=True # Auto-fix for local development
161+
)
162+
163+
result = extensions.tables.upload_parquet_file(
164+
graph_id="your-graph-id",
165+
table_name="Entity",
166+
file_path=Path("data/entities.parquet"),
167+
options=upload_options
168+
)
169+
170+
if result.success:
171+
print(f"✅ Uploaded {result.row_count:,} rows")
172+
else:
173+
print(f"❌ Upload failed: {result.error}")
174+
175+
# Ingest the uploaded tables
176+
ingest_options = IngestOptions(
177+
ignore_errors=True, # Continue on errors
178+
rebuild=False, # Don't rebuild existing data
179+
on_progress=lambda msg: print(f"Ingest: {msg}")
180+
)
181+
182+
ingest_result = extensions.tables.ingest_all_tables(
183+
graph_id="your-graph-id",
184+
options=ingest_options
185+
)
186+
```
187+
188+
### Querying Data
189+
190+
```python
191+
# Simple query
192+
result = extensions.query.query(
193+
graph_id="your-graph-id",
194+
query="MATCH (n:Entity) RETURN count(n) AS total"
195+
)
196+
197+
print(f"Total nodes: {result.data[0]['total']}")
198+
199+
# Query with parameters
200+
result = extensions.query.query(
201+
graph_id="your-graph-id",
202+
query="MATCH (n:Entity) WHERE n.ticker = $ticker RETURN n",
203+
parameters={"ticker": "AAPL"}
204+
)
205+
206+
for node in result.data:
207+
print(f"Found: {node}")
208+
```
209+
210+
## Environment Variables
211+
212+
You can also use environment variables for configuration:
213+
214+
```bash
215+
export ROBOSYSTEMS_API_URL="http://localhost:8000"
216+
export ROBOSYSTEMS_API_KEY="your-api-key"
217+
export ROBOSYSTEMS_GRAPH_ID="your-graph-id"
218+
```
219+
220+
Then reference them in your code:
221+
```python
222+
import os
223+
224+
config = RoboSystemsExtensionConfig(
225+
base_url=os.getenv("ROBOSYSTEMS_API_URL", "http://localhost:8000"),
226+
headers={"X-API-Key": os.getenv("ROBOSYSTEMS_API_KEY")}
227+
)
228+
```
229+
230+
## Comparison with Raw API Approach
231+
232+
| Operation | Raw httpx Calls | SDK with Extensions | Lines of Code Reduction |
233+
|-----------|----------------|---------------------|------------------------|
234+
| Upload file to table | ~25 lines (3 API calls) | ~6 lines (1 method) | **76% reduction** |
235+
| Query graph | ~10 lines | ~3 lines | **70% reduction** |
236+
| List tables | ~8 lines | ~2 lines | **75% reduction** |
237+
238+
**Benefits of Using the SDK:**
239+
- Type-safe model classes
240+
- Automatic error handling
241+
- Progress callbacks
242+
- Connection pooling
243+
- Cleaner, more maintainable code
244+
- Built-in support for async operations
245+
246+
## Additional Resources
247+
248+
- **API Documentation:** https://api.robosystems.ai/docs
249+
- **Main Repository:** https://github.com/RoboSystems/robosystems-python-client
250+
- **Extension Documentation:** See `robosystems_client/extensions/README.md`
251+
252+
## Getting Help
253+
254+
If you encounter issues:
255+
1. Check the error message and stack trace
256+
2. Verify your API key and graph ID are correct
257+
3. Ensure the API server is running (for local development)
258+
4. Check the API documentation for endpoint changes
259+
5. Open an issue on GitHub with a minimal reproducible example
260+
261+
## Contributing
262+
263+
Have a useful example to share? Contributions are welcome!
264+
265+
1. Fork the repository
266+
2. Create a new example file following the existing patterns
267+
3. Update this README with your example
268+
4. Submit a pull request
269+
270+
---
271+
272+
**Happy coding with RoboSystems! 🤖**

‎examples/basic_query.py‎

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
"""
2+
Simple example of querying a RoboSystems graph using the Python SDK.
3+
4+
This example demonstrates the simplest way to execute queries against
5+
an existing graph using the RoboSystems Python Client SDK.
6+
7+
Usage:
8+
python examples/basic_query.py --api-key <your-api-key> --graph-id <graph-id>
9+
"""
10+
11+
import argparse
12+
import json
13+
import sys
14+
15+
from robosystems_client.extensions import (
16+
RoboSystemsExtensions,
17+
RoboSystemsExtensionConfig,
18+
)
19+
20+
21+
def run_query_example(
22+
api_key: str, graph_id: str, base_url: str = "http://localhost:8000"
23+
):
24+
"""Run simple query examples against a graph."""
25+
print("\n" + "=" * 60)
26+
print("🔍 RoboSystems Query Example (SDK)")
27+
print("=" * 60)
28+
29+
# Initialize extensions with API key
30+
config = RoboSystemsExtensionConfig(base_url=base_url, headers={"X-API-Key": api_key})
31+
extensions = RoboSystemsExtensions(config)
32+
33+
# Example queries
34+
queries = [
35+
{"name": "Count all nodes", "query": "MATCH (n) RETURN count(n) AS total_nodes"},
36+
{
37+
"name": "Count nodes by label",
38+
"query": "MATCH (n) RETURN labels(n) AS label, count(n) AS count ORDER BY count DESC LIMIT 10",
39+
},
40+
{"name": "Sample nodes", "query": "MATCH (n) RETURN n LIMIT 5"},
41+
]
42+
43+
for example in queries:
44+
print(f"\n📊 {example['name']}")
45+
print(f" Query: {example['query']}")
46+
47+
try:
48+
# Execute the query
49+
result = extensions.query.query(graph_id, example["query"])
50+
51+
# Display results
52+
if hasattr(result, "data") and result.data:
53+
print(f" ✅ Returned {len(result.data)} records")
54+
55+
# Pretty print results
56+
if len(result.data) <= 10:
57+
print(" Results:")
58+
print(" " + json.dumps(result.data, indent=4).replace("\n", "\n "))
59+
else:
60+
print(f" Showing first 10 of {len(result.data)} records:")
61+
print(" " + json.dumps(result.data[:10], indent=4).replace("\n", "\n "))
62+
else:
63+
print(" ⚠️ No results returned")
64+
65+
except Exception as e:
66+
print(f" ❌ Query failed: {e}")
67+
68+
# Cleanup
69+
extensions.close()
70+
71+
print("\n" + "=" * 60)
72+
print("✅ Query examples complete!")
73+
print("=" * 60 + "\n")
74+
75+
76+
def main():
77+
parser = argparse.ArgumentParser(description="Simple RoboSystems query example")
78+
parser.add_argument("--api-key", required=True, help="Your RoboSystems API key")
79+
parser.add_argument("--graph-id", required=True, help="The graph ID to query")
80+
parser.add_argument(
81+
"--base-url",
82+
default="http://localhost:8000",
83+
help="API base URL (default: http://localhost:8000)",
84+
)
85+
86+
args = parser.parse_args()
87+
88+
try:
89+
run_query_example(args.api_key, args.graph_id, args.base_url)
90+
except Exception as e:
91+
print(f"\n❌ Error: {e}")
92+
import traceback
93+
94+
traceback.print_exc()
95+
sys.exit(1)
96+
97+
98+
if __name__ == "__main__":
99+
main()

0 commit comments

Comments
 (0)