# GigaBrain API Documentation GigaBrain provides both REST and gRPC APIs for graph database operations. This documentation covers both interfaces. ## Table of Contents - [Authentication](#authentication) - [REST API](#rest-api) - [gRPC API](#grpc-api) - [Error Handling](#error-handling) - [Examples](#examples) ## Authentication GigaBrain uses JWT (JSON Web Tokens) for authentication. Include the token in the `Authorization` header: ``` Authorization: Bearer ``` ### Roles - **Admin**: Full access to all operations including user management - **ReadWrite**: Can read and modify graph data - **ReadOnly**: Can only read graph data ## REST API Base URL: `http://localhost:3000/api/v1` ### Health Check **GET** `/health` Returns server health status. **Response:** ```json { "status": "healthy", "version": "0.1.0", "uptime_seconds": 3600 } ``` ### Nodes #### Create Node **POST** `/nodes` Creates a new node in the graph. **Request Body:** ```json { "labels": ["Person", "Employee"], "properties": { "name": "John Doe", "age": 30, "active": true, "salary": 75000.50 } } ``` **Response:** ```json { "node_id": 12345 } ``` #### Get Node **GET** `/nodes/{node_id}` Retrieves a node by its ID. **Response:** ```json { "node": { "id": 12345, "labels": ["Person", "Employee"], "properties": { "name": "John Doe", "age": 30, "active": true, "salary": 75000.50 } } } ``` #### Update Node **PUT** `/nodes/{node_id}` Updates an existing node's labels and/or properties. Labels are completely replaced if provided, while properties are merged with existing ones. **Request Body:** ```json { "labels": ["Person", "Manager"], "properties": { "title": "Engineering Manager", "department": "Technology", "team_size": 8 } } ``` **Response:** ```json { "id": 12345, "labels": ["Person", "Manager"], "properties": { "name": "John Doe", "age": 30, "title": "Engineering Manager", "department": "Technology", "team_size": 8 } } ``` **Notes:** - Labels: If provided, completely replace existing labels - Properties: If provided, merge with existing properties (new properties are added, existing ones are updated) - Both `labels` and `properties` fields are optional #### Delete Node Property **DELETE** `/nodes/{node_id}/properties/{property_key}` Deletes a specific property from a node. **Response:** ```json { "id": 12345, "labels": ["Person", "Manager"], "properties": { "name": "John Doe", "age": 30, "department": "Technology" } } ``` **Error Response (404):** ```json { "error": "Property 'salary' not found", "code": 404 } ``` #### Delete Node **DELETE** `/nodes/{node_id}` Deletes a node from the graph. **Response:** - Status: `204 No Content` - Body: Empty ### Relationships #### Create Relationship **POST** `/relationships` Creates a new relationship between two nodes. **Request Body:** ```json { "start_node": { "id": 12345 }, "end_node": { "id": 67890 }, "rel_type": "WORKS_FOR", "properties": [ { "key": "since", "value": { "string_value": "2023-01-01" } } ] } ``` **Response:** ```json { "relationship_id": { "id": 98765 } } ``` #### Get Relationship **GET** `/relationships/{relationship_id}` Retrieves a relationship by its ID. **Response:** ```json { "relationship": { "id": { "id": 98765 }, "start_node": { "id": 12345 }, "end_node": { "id": 67890 }, "rel_type": "WORKS_FOR", "properties": [] } } ``` #### Delete Relationship **DELETE** `/relationships/{relationship_id}` Deletes a relationship from the graph. **Response:** ```json { "success": true } ``` ### Cypher Queries #### Execute Cypher Query **POST** `/cypher` Executes a Cypher query against the graph. **Request Body:** ```json { "query": "MATCH (n:Person) WHERE n.age > 25 RETURN n.name, n.age", "parameters": {} } ``` **Response:** ```json { "results": [ { "columns": ["n.name", "n.age"], "data": [ ["John Doe", 30], ["Jane Smith", 28] ] } ], "error": "", "execution_time_ms": 15 } ``` ### Graph Algorithms #### Shortest Path **POST** `/algorithms/shortest-path` Finds the shortest path between two nodes. **Request Body:** ```json { "start_node": { "id": 12345 }, "end_node": { "id": 67890 }, "max_depth": 10 } ``` **Response:** ```json { "path": [ {"id": 12345}, {"id": 54321}, {"id": 67890} ], "total_weight": 2.0 } ``` #### PageRank **POST** `/algorithms/pagerank` Calculates PageRank scores for specified nodes. **Request Body:** ```json { "nodes": [ {"id": 12345}, {"id": 67890} ], "damping_factor": 0.85, "max_iterations": 100, "tolerance": 0.0001 } ``` **Response:** ```json { "rankings": { "12345": 0.15, "67890": 0.25 } } ``` #### Centrality **POST** `/algorithms/centrality` Calculates various centrality measures. **Request Body:** ```json { "algorithm": "betweenness", "nodes": [ {"id": 12345}, {"id": 67890} ] } ``` **Response:** ```json { "centrality": { "12345": 0.35, "67890": 0.42 } } ``` #### Community Detection **POST** `/algorithms/community-detection` Detects communities in the graph. **Request Body:** ```json { "algorithm": "louvain", "resolution": 1.0 } ``` **Response:** ```json { "communities": [ [12345, 23456, 34567], [67890, 78901, 89012] ], "modularity": 0.45 } ``` ### Graph Statistics #### Get Graph Stats **GET** `/stats` Returns statistics about the graph. **Response:** ```json { "node_count": 1000, "relationship_count": 2500, "relationship_types": ["KNOWS", "WORKS_FOR", "LIVES_IN"], "labels": ["Person", "Company", "City"] } ``` ### API Documentation #### Get API Documentation **GET** `/docs` Returns this API documentation in JSON format. ### Schema Constraints #### Create Constraint **POST** `/constraints` Creates a new schema constraint to enforce data integrity rules. **Request Body:** ```json { "constraint_type": "required", "label": "Employee", "property": "email" } ``` **Constraint Types:** 1. **Required Constraint** ```json { "constraint_type": "required", "label": "Employee", "property": "email" } ``` 2. **Type Constraint** ```json { "constraint_type": "type", "label": "Employee", "property": "salary", "type_value": "integer" } ``` Supported types: `string`, `integer`, `float`, `boolean` 3. **Range Constraint** ```json { "constraint_type": "range", "label": "Employee", "property": "salary", "min_value": 30000, "max_value": 200000 } ``` 4. **Pattern Constraint** ```json { "constraint_type": "pattern", "label": "User", "property": "email", "pattern": "@" } ``` 5. **Enum Constraint** ```json { "constraint_type": "enum", "label": "Task", "property": "status", "allowed_values": ["pending", "in_progress", "completed"] } ``` **Response:** ```json { "id": "required:Employee:email", "constraint_type": "required", "label": "Employee", "property": "email", "details": {} } ``` #### List Constraints **GET** `/constraints` Lists all defined schema constraints. **Response:** ```json [ { "id": "required:Employee:email", "constraint_type": "required", "label": "Employee", "property": "email", "details": {} }, { "id": "type:Employee:salary", "constraint_type": "type", "label": "Employee", "property": "salary", "details": { "type": "Integer" } } ] ``` ## gRPC API The gRPC API provides the same functionality as the REST API but uses Protocol Buffers for serialization. The service is defined in `proto/gigabrain.proto`. ### Service Definition ```protobuf service GigaBrainService { // Node operations rpc CreateNode(CreateNodeRequest) returns (CreateNodeResponse); rpc GetNode(GetNodeRequest) returns (GetNodeResponse); rpc UpdateNode(UpdateNodeRequest) returns (UpdateNodeResponse); rpc DeleteNode(DeleteNodeRequest) returns (DeleteNodeResponse); // Relationship operations rpc CreateRelationship(CreateRelationshipRequest) returns (CreateRelationshipResponse); rpc GetRelationship(GetRelationshipRequest) returns (GetRelationshipResponse); rpc DeleteRelationship(DeleteRelationshipRequest) returns (DeleteRelationshipResponse); // Query operations rpc ExecuteCypher(CypherQueryRequest) returns (CypherQueryResponse); // Algorithm operations rpc ShortestPath(ShortestPathRequest) returns (ShortestPathResponse); rpc PageRank(PageRankRequest) returns (PageRankResponse); rpc Centrality(CentralityRequest) returns (CentralityResponse); rpc CommunityDetection(CommunityDetectionRequest) returns (CommunityDetectionResponse); // Stats operations rpc GetGraphStats(GraphStatsRequest) returns (GraphStatsResponse); } ``` ### Connection Connect to the gRPC server at `localhost:50051`. ### Property Values Property values can be one of the following types: - `string_value`: String data - `int_value`: 64-bit integer - `float_value`: 64-bit floating point - `bool_value`: Boolean - `bytes_value`: Binary data ## Error Handling ### HTTP Status Codes - `200 OK`: Successful operation - `400 Bad Request`: Invalid request data - `401 Unauthorized`: Authentication required - `403 Forbidden`: Insufficient permissions - `404 Not Found`: Resource not found - `500 Internal Server Error`: Server error ### Error Response Format ```json { "error": "Node ID is required", "code": 400 } ``` ### gRPC Status Codes - `OK`: Successful operation - `INVALID_ARGUMENT`: Invalid request parameters - `NOT_FOUND`: Resource not found - `INTERNAL`: Internal server error - `UNAUTHENTICATED`: Authentication failed - `PERMISSION_DENIED`: Authorization failed ## Examples ### Creating a Social Network ```bash # Create users curl -X POST http://localhost:3000/api/v1/nodes \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "labels": ["Person"], "properties": { "name": "Alice", "age": 25 } }' curl -X POST http://localhost:3000/api/v1/nodes \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "labels": ["Person"], "properties": { "name": "Bob", "age": 30 } }' # Create friendship curl -X POST http://localhost:3000/api/v1/relationships \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "start_node": 1, "end_node": 2, "rel_type": "FRIENDS", "properties": { "since": "2023-01-01" } }' # Find mutual friends curl -X POST http://localhost:3000/api/v1/cypher \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "query": "MATCH (a:Person)-[:FRIENDS]-(mutual)-[:FRIENDS]-(b:Person) WHERE a.name = $name1 AND b.name = $name2 RETURN mutual.name", "parameters": {"name1": "Alice", "name2": "Bob"} }' # Update a node curl -X PUT http://localhost:3000/api/v1/nodes/1 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "labels": ["Person", "VIP"], "properties": { "status": "premium", "last_seen": "2023-12-01" } }' # Delete a specific property curl -X DELETE http://localhost:3000/api/v1/nodes/1/properties/age \ -H "Authorization: Bearer " ``` ### Working with Schema Constraints ```bash # Create a required email constraint for Employee nodes curl -X POST http://localhost:3000/api/v1/constraints \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "constraint_type": "required", "label": "Employee", "property": "email" }' # Create a type constraint for salary curl -X POST http://localhost:3000/api/v1/constraints \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "constraint_type": "type", "label": "Employee", "property": "salary", "type_value": "integer" }' # Create a range constraint for salary curl -X POST http://localhost:3000/api/v1/constraints \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "constraint_type": "range", "label": "Employee", "property": "salary", "min_value": 30000, "max_value": 200000 }' # Try to create an employee without email (will fail) curl -X POST http://localhost:3000/api/v1/nodes \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "labels": ["Employee"], "properties": { "name": "John Doe", "salary": 50000 } }' # Response: {"error": "Validation error: Required property 'email' is missing", "code": 400} # Create an employee with all required properties curl -X POST http://localhost:3000/api/v1/nodes \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "labels": ["Employee"], "properties": { "name": "John Doe", "email": "john@example.com", "salary": 50000 } }' ``` ### Running Graph Algorithms ```bash # Calculate shortest path curl -X POST http://localhost:3000/api/v1/algorithms/shortest-path \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "start_node": 1, "end_node": 10, "relationship_types": ["FRIENDS", "KNOWS"] }' # Run PageRank curl -X POST http://localhost:3000/api/v1/algorithms/pagerank \ -H "Content-Type: application/json" \ -H "Authorization: Bearer " \ -d '{ "nodes": [1, 2, 3], "damping_factor": 0.85 }' ``` ## Performance Considerations - Use batch operations when creating multiple nodes/relationships - Enable request compression for large payloads - Consider using gRPC for high-performance scenarios - Implement connection pooling for production use - Use streaming for large result sets ## Rate Limiting The API implements rate limiting to prevent abuse: - **Default limit**: 1000 requests per minute per IP - **Burst limit**: 100 requests per second - **Headers**: `X-RateLimit-Remaining`, `X-RateLimit-Reset` ## Monitoring Monitor API performance using the built-in metrics: - Request count and duration - Error rates by endpoint - Active connections - Memory and CPU usage Access metrics at: `GET /metrics` (Prometheus format)