### Quick Start: Minimal jvspatial Server Setup Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md A minimal example demonstrating how to quickly set up a jvspatial Server instance with a basic Walker endpoint. This example includes server initialization with database and authentication configuration, defining a POST endpoint for data processing, and running the server. It's suitable for getting started but production-ready implementations should refer to standard examples. ```python from jvspatial.api import Server, endpoint from jvspatial.api.decorators import EndpointField from jvspatial.core import Walker, Node, on_visit from jvspatial.api.config_groups import DatabaseConfig, AuthConfig # Create a server instance server = Server( title="My Spatial API", description="A spatial data management API", version="1.0.0", debug=True, database=DatabaseConfig(db_type="json", db_path="./jvdb"), auth=AuthConfig(auth_enabled=False) # Set to True to enable authentication ) # Define a Walker endpoint @endpoint("/process", methods=["POST"]) class ProcessData(Walker): data: str = EndpointField(description="Data to process") @on_visit(Node) async def process(self, here): self.response["result"] = self.data.upper() # Run the server if __name__ == "__main__": server.run() ``` -------------------------------- ### Running jvspatial Examples (Bash) Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/quick-start-guide.md Provides instructions on how to navigate to the examples directory and run various jvspatial example scripts using Python. ```bash cd examples/ ls -la # Run examples python core/cities.py python server/server_demo.py python walkers/walker_traversal_demo.py ``` -------------------------------- ### Complete Authenticated Server Example with jvspatial Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md This concise Python script provides a complete, runnable example of an authenticated jvspatial server in under 20 lines. It demonstrates configuring authentication, adding an `AuthenticationMiddleware`, defining public, protected, and admin endpoints, and programmatically creating an initial admin user on startup. ```python from jvspatial.api import create_server, endpoint from jvspatial.api.auth import configure_auth, AuthenticationMiddleware, User # Configure authentication configure_auth(jwt_secret_key="demo-secret-key") # Create server with middleware server = create_server(title="Quick Auth Demo") server.app.add_middleware(AuthenticationMiddleware) @endpoint("/public") async def public(): return {"message": "Public data"} @endpoint("/protected", auth=True) async def protected(): return {"message": "Protected data"} @endpoint("/admin", auth=True, roles=["admin"]) async def admin(): return {"message": "Admin only"} @server.on_startup async def setup(): if not await User.find_by_username("admin"): await User.create(username="admin", email="admin@test.com", password_hash=User.hash_password("admin123"), is_admin=True) server.run() if __name__ == "__main__" else None ``` -------------------------------- ### User Creation via API (curl) Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md Command-line examples using curl to register and log in a user, obtaining a JWT token. ```APIDOC ## Register User ```bash curl -X POST "http://localhost:8000/auth/register" \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "email": "admin@example.com", "password": "admin123", "confirm_password": "admin123" }' ``` ## Login User ```bash curl -X POST "http://localhost:8000/auth/login" \ -H "Content-Type: application/json" \ -d '{ "username": "admin", "password": "admin123" }' ``` ``` -------------------------------- ### Authentication Server Setup Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md This snippet shows how to create a jvspatial server with authentication enabled, automatically registering endpoints for registration, login, and logout. ```APIDOC ## POST /auth/register ### Description Registers a new user for the authenticated API. ### Method POST ### Endpoint /auth/register ### Parameters #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. - **confirm_password** (string) - Required - Confirmation of the password. ### Response #### Success Response (200) - **message** (string) - Indicates successful user registration. ## POST /auth/login ### Description Logs in a user and returns a JWT token for authentication. ### Method POST ### Endpoint /auth/login ### Parameters #### Request Body - **username** (string) - Required - The username of the user. - **password** (string) - Required - The password of the user. ### Response #### Success Response (200) - **access_token** (string) - The JWT token for authenticating subsequent requests. - **token_type** (string) - The type of token, usually 'bearer'. ## POST /auth/logout ### Description Logs out the currently authenticated user. ### Method POST ### Endpoint /auth/logout ### Response #### Success Response (200) - **message** (string) - Indicates successful logout. ``` -------------------------------- ### API Key Generation and Usage Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md Shows how to programmatically create API keys for users and demonstrates how these keys can be used in subsequent requests for authentication. Includes both Python code for creation and a cURL example for usage. ```python # Create API key for a user @endpoint("/create-api-key", auth=True, methods=["POST"]) async def create_key(request: Request): from jvspatial.api.auth import APIKey, get_current_user user = get_current_user(request) api_key = await APIKey.create( name="My Service Key", key_id="service-key-1", key_hash=APIKey.hash_key("secret-key-123"), user_id=user.id ) return {"key_id": api_key.key_id, "secret": "secret-key-123"} # Use API key in requests # curl -H "X-API-Key: secret-key-123" http://localhost:8000/protected/data ``` -------------------------------- ### Server Configuration and Start Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/quick-start-guide.md Demonstrates how to configure and start the jvspatial server, including setting host, port, and title. ```APIDOC ## Server Start ### Description Starts the jvspatial server with specified configuration. ### Method N/A (Script Execution) ### Endpoint N/A ### Parameters (Configuration is set within the `ServerConfig` object) ### Request Example ```python import asyncio from jvspatial.api import Server, ServerConfig async def main(): # Create server with configuration server = Server( config=ServerConfig( host="0.0.0.0", port=8000, title="My First jvspatial App", ) ) # Start server await server.start() if __name__ == "__main__": asyncio.run(main()) ``` ### Response (Server starts listening for requests on the configured host and port.) ### Usage Run the Python script (e.g., `app.py`) to start the server. Access interactive API documentation at `http://localhost:8000/docs`. ``` -------------------------------- ### Testing Authentication Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md Examples of how to use the obtained JWT token to access protected and admin endpoints. ```APIDOC ## Access Protected Endpoint ```bash TOKEN="your-jwt-token-here" curl -H "Authorization: Bearer $TOKEN" \ "http://localhost:8000/protected/data" ``` ## Access Admin Endpoint ```bash TOKEN="your-jwt-token-here" curl -H "Authorization: Bearer $TOKEN" \ "http://localhost:8000/admin/users" ``` ``` -------------------------------- ### Quick Start Example Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md A minimal example demonstrating how to set up and run a jvspatial server with a basic Walker endpoint. ```APIDOC ## Quick Start ### Description A minimal example to get started quickly with jvspatial. It demonstrates server instantiation, defining a Walker endpoint, and running the server. ### Method POST ### Endpoint /process ### Parameters #### Request Body - **data** (str) - Required - Data to process ### Request Example ```json { "data": "sample data" } ``` ### Response #### Success Response (200) - **result** (str) - The processed data in uppercase. #### Response Example ```json { "result": "SAMPLE DATA" } ``` ### Code Example ```python from jvspatial.api import Server, endpoint from jvspatial.api.decorators import EndpointField from jvspatial.core import Walker, Node, on_visit from jvspatial.api.config_groups import DatabaseConfig, AuthConfig server = Server( title="My Spatial API", description="A spatial data management API", version="1.0.0", debug=True, database=DatabaseConfig(db_type="json", db_path="./jvdb"), auth=AuthConfig(auth_enabled=False) # Set to True to enable authentication ) @endpoint("/process", methods=["POST"]) class ProcessData(Walker): data: str = EndpointField(description="Data to process") @on_visit(Node) async def process(self, here): self.response["result"] = self.data.upper() if __name__ == "__main__": server.run() ``` ``` -------------------------------- ### Install jvspatial Package Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/quick-start-guide.md Installs the jvspatial library using pip. Supports installation with optional dependencies for Redis cache, S3 storage, or all optional dependencies. ```bash pip install jvspatial pip install jvspatial[redis] # For Redis cache pip install jvspatial[s3] # For S3 storage pip install jvspatial[all] # All optional deps ``` -------------------------------- ### Endpoint Access Control Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md Demonstrates how to secure endpoints with authentication, specific permissions, and roles. ```APIDOC ## GET /reports ### Description Retrieves a list of available reports. Requires authentication and 'read_reports' permission. ### Method GET ### Endpoint /reports ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **reports** (array) - A list of report names. #### Response Example ```json { "reports": [ "Monthly", "Weekly" ] } ``` ## GET /analyze ### Description Performs data analysis. Requires authentication and 'analyst' or 'admin' roles. ### Method GET ### Endpoint /analyze ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **analysis** (string) - The results of the data analysis. #### Response Example ```json { "analysis": "Complex analysis results" } ``` ## GET /advanced ### Description Executes advanced operations. Requires authentication, 'advanced_ops' permission, and 'admin' role. ### Method GET ### Endpoint /advanced ### Parameters #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **message** (string) - A confirmation message for advanced operations. #### Response Example ```json { "message": "Advanced operations" } ``` ``` -------------------------------- ### Complete JVspatial Application Example Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/import-patterns.md A comprehensive example demonstrating recommended import patterns and building a complete application with custom nodes, walkers, and endpoints. ```python """Example application showing recommended import patterns.""" # Standard library import asyncio from typing import Optional # Third-party (if any) # import httpx # JVspatial - Core from jvspatial import ( Node, Edge, Walker, Root, GraphContext, ) # JVspatial - API from jvspatial.api import ( Server, ServerConfig, endpoint, ) # JVspatial - Database from jvspatial.db import ( create_database, Database, ) # JVspatial - Cache from jvspatial.cache import get_cache_backend # JVspatial - Utils from jvspatial.utils import ( memoize, retry, NodeId, is_dict, ) # Your custom nodes class User(Node): name: str email: str # Your custom walkers class UserWalker(Walker): @on_visit async def visit_user(self, node: User): return {"user": node.to_dict()} # Your endpoints @endpoint("/users/{user_id}") async def get_user(user_id: str): async with GraphContext() as ctx: user = await User.get(user_id, ctx=ctx) return {"user": user.to_dict()} # Server setup async def main(): server = Server( config=ServerConfig( host="0.0.0.0", port=8000, ) ) await server.start() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Example Walker from Installable Package Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md Provides a Python code example for a Walker class within an installable package. It uses register_walker_to_default to register the walker and defines processing logic. ```python # my_walkers/walkers.py from jvspatial.api import register_walker_to_default from jvspatial.api.endpoint.router import EndpointField from jvspatial.core import Walker, Root, on_visit @register_walker_to_default("/my-package/process") class MyPackageWalker(Walker): """Walker from installable package.""" input_data: str = EndpointField( description="Data to process", examples=["hello", "world"] ) @on_visit(Root) async def process_data(self, here): # Package-specific processing logic self.response = { "processed": self.input_data.upper(), "package": "my_walkers", "version": "1.0.0" } ``` -------------------------------- ### Run jvspatial Application from Command Line Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/quick-start-guide.md Executes a Python application file (e.g., app.py) that starts the jvspatial server. Provides instructions on how to access the interactive API documentation. ```bash python app.py Visit: http://localhost:8000/docs for interactive API documentation! ``` -------------------------------- ### API Key Management Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md Endpoints for creating API keys for users and using them for authentication. ```APIDOC ## POST /create-api-key ### Description Creates a new API key for the authenticated user. ### Method POST ### Endpoint /create-api-key ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **key_id** (string) - The ID of the newly created API key. - **secret** (string) - The secret key for the API key. #### Response Example ```json { "key_id": "service-key-1", "secret": "secret-key-123" } ``` ## Using API Keys ### Description Use the generated API key's secret in the `X-API-Key` header for authenticated requests to protected endpoints. ### Method GET (example for a protected endpoint) ### Endpoint `http://localhost:8000/protected/data` ### Headers - **X-API-Key**: `your-api-key-secret` ``` -------------------------------- ### Start jvspatial Server Application in Python Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/quick-start-guide.md An asynchronous Python script to initialize and start a jvspatial Server. It configures the server's host, port, and title, then starts the server. ```python import asyncio async def main(): # Create server server = Server( config=ServerConfig( host="0.0.0.0", port=8000, title="My First jvspatial App", ) ) # Start server await server.start() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Protected Endpoints Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md Demonstrates how to define public, protected (login required), and admin-only endpoints using decorators. ```APIDOC ## GET /public/info ### Description An example of a public endpoint that does not require authentication. ### Method GET ### Endpoint /public/info ### Response #### Success Response (200) - **message** (string) - A message indicating the endpoint is publicly accessible. ## GET /protected/data ### Description An example of a protected endpoint that requires the user to be logged in. ### Method GET ### Endpoint /protected/data ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., 'Bearer YOUR_JWT_TOKEN'). ### Response #### Success Response (200) - **message** (string) - A message indicating the endpoint is protected and requires login. ## GET /admin/users ### Description An example of an admin-only endpoint that requires the user to be logged in and have the 'admin' role. ### Method GET ### Endpoint /admin/users ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication (e.g., 'Bearer YOUR_JWT_TOKEN'). ### Response #### Success Response (200) - **message** (string) - A message indicating the endpoint is accessible only to administrators. ``` -------------------------------- ### Server Setup and Configuration Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Demonstrates basic and advanced server setup for the jvspatial API using FastAPI, including database and CORS configuration. ```APIDOC ## Server Setup and Configuration ### Description Basic server setup and advanced configuration options for the jvspatial API using FastAPI. ### Method N/A (Server Initialization) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from jvspatial.api import Server, ServerConfig, endpoint, walker_endpoint from jvspatial.api.endpoint.router import EndpointField from jvspatial.core import Node, Walker from jvspatial.core.entities import on_visit # Basic server setup server = Server( title="My Spatial API", description="Graph-based spatial data management API", version="1.0.0", host="0.0.0.0", port=8000, debug=True # Enable for development ) # Advanced server configuration advanced_config = ServerConfig( title="Production Spatial API", description="Enterprise graph data API", version="2.0.0", host="0.0.0.0", port=8080, # Database configuration db_type="mongodb", db_connection_string="mongodb://localhost:27017", db_database_name="spatial_db", # CORS settings cors_enabled=True, cors_origins=["https://myapp.com", "http://localhost:3000"], # API documentation docs_url="/api/docs", redoc_url="/api/redoc", log_level="info" ) production_server = Server(config=advanced_config) ``` ### Response #### Success Response (200) N/A (Server initialization does not return a response in this context) #### Response Example N/A ``` -------------------------------- ### Write API Test for Get User Endpoint (Python) Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/quick-start-guide.md Provides an example of an API test using pytest and httpx to test the get user endpoint of a jvspatial server. It sends a GET request and asserts the response status code and JSON data. Dependencies include pytest, httpx.AsyncClient, and jvspatial.api.Server. ```python import pytest from httpx import AsyncClient from jvspatial.api import Server @pytest.mark.asyncio async def test_get_user_endpoint(): """Test the get user endpoint.""" server = Server() async with AsyncClient(app=server.app, base_url="http://test") as client: response = await client.get("/users/test_id") assert response.status_code == 200 data = response.json() assert "user" in data ``` -------------------------------- ### Documentation Maintenance Guidelines Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Provides guidelines for maintaining project documentation, including updating the README file with feature changes, installation instructions, and usage examples. It also outlines the procedure for updating the `docs/` directory, ensuring API references, guides, architecture documents, and examples are kept current. ```markdown ## Documentation Maintenance ### README Updates When adding new features: 1. **Review existing README.md** 2. **Update feature list** if adding major functionality 3. **Update installation/setup** if dependencies change 4. **Update usage examples** to reflect new capabilities 5. **Maintain consistency** with existing documentation style ### Documentation Directory Always review and update `docs/` directory: ``` docs/ ├── api/ # API reference documentation ├── guides/ # User guides and tutorials ├── architecture/ # System design documents └── examples/ # Code examples and tutorials ``` **Update procedure:** 1. Check if new feature requires new documentation files 2. Update existing API documentation for modified classes/methods 3. Add user guides for complex features 4. Update architecture docs if design patterns change ``` -------------------------------- ### Run Authentication Demo Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/examples.md This bash script navigates to the examples directory and runs the authentication demo script. It also lists the URLs for accessing the dashboard, API docs, and various endpoints. ```bash cd examples/ python auth_demo.py ``` -------------------------------- ### Basic Server Setup Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Sets up a basic jvspatial API server with a title, description, version, host, and port. ```APIDOC ## Basic Server Setup ### Description Sets up a basic jvspatial API server instance. ### Method N/A (Initialization) ### Endpoint N/A ### Parameters None ### Request Example ```python from jvspatial.api import Server server = Server( title="My Spatial API", description="Graph-based spatial data management API", version="1.0.0", host="0.0.0.0", port=8000 ) if __name__ == "__main__": server.run() ``` ### Response N/A ``` -------------------------------- ### Create API Endpoint for User Retrieval in Python Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/quick-start-guide.md Sets up a jvspatial Server and defines a GET endpoint '/users/{user_id}' to retrieve a user by ID. It uses the User.get() method and handles potential 404 errors. ```python from jvspatial.api import Server, endpoint from jvspatial.core import Node # Create server (entity-centric operations are automatically available) server = Server( title="My API", description="API description", version="1.0.0", db_type="json", db_path="./jvdb", auth_enabled=False # Set to True to enable authentication ) @endpoint("/users/{user_id}", methods=["GET"]) async def get_user(user_id: str): """Get a user by ID.""" user = await User.get(user_id) # Entity-centric operation if not user: from fastapi import HTTPException raise HTTPException(status_code=404, detail="User not found") return {"user": await user.export()} ``` -------------------------------- ### Examples Maintenance Guidelines Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Outlines the process for maintaining example code within the jvspatial project. This includes organizing examples into `basic/` and `advanced/` directories, ensuring specific examples for query interfaces and semantic filtering are up-to-date, and managing migration guides if necessary. ```markdown ## 💡 Examples Maintenance ### Example Directory Structure ``` examples/ ├── basic/ # Simple usage examples ├── advanced/ # Complex scenarios ├── query_interface_example.py # Comprehensive entity-centric CRUD operations ├── semantic_filtering.py # Advanced semantic filtering with Node.nodes() └── migration/ # Migration guides (if needed) ``` ``` -------------------------------- ### Running jvspatial Examples via Bash Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/examples.md Provides instructions on how to run individual jvspatial example scripts from the command line. This enables users to test specific functionalities directly. ```bash cd examples/ python walker_traversal_demo.py python travel_graph.py python agent_graph.py # ... etc ``` -------------------------------- ### API Usage Examples with Curl Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Provides command-line examples using curl to interact with jvspatial API endpoints. Demonstrates making POST requests with JSON payloads for Walker endpoints, GET requests for function endpoints, and how to include path and query parameters. Also mentions the automatic availability of Swagger UI and ReDoc documentation. ```bash # Walker endpoint - POST request with parameters curl -X POST "http://localhost:8000/api/users/process" \ -H "Content-Type: application/json" \ -d '{ "user_name": "John Doe", "department": "engineering", "include_inactive": false, "max_connections": 5, "start_node": "n:Root:root" }' # Function endpoint - GET request curl "http://localhost:8000/api/users/count" # Function endpoint with path parameters curl "http://localhost:8000/api/cities/CA" # Function endpoint with query parameters curl "http://localhost:8000/api/users/paginated?page=1&page_size=10&department=engineering" # API documentation is automatically available # http://localhost:8000/docs (Swagger UI) # http://localhost:8000/redoc (ReDoc) ``` -------------------------------- ### Create Server with Enhanced Configuration (Python) Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/examples.md This Python code snippet demonstrates creating a server instance with enhanced configuration options, including title, description, version, debug mode, database type, and database path. ```python server = create_server( title="Dynamic Task Management API", description="Advanced task management with dynamic endpoint registration", version="2.0.0", debug=True, db_type="json", db_path="jvdb/dynamic_demo", ) ``` -------------------------------- ### Example: Create and Use jvspatial Database Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/import-patterns.md Provides a practical example of using the 'create_database' function from 'jvspatial.db' to instantiate different database backends. It shows how to configure a JSON database with a base path and a MongoDB database with connection details. ```python from jvspatial.db import create_database # Create database instance db = create_database("json", base_path="./data") # Or for MongoDB db = create_database("mongodb", db_name="mydb", connection_string="mongodb://localhost:27017") ``` -------------------------------- ### Exposing Simple Function as API Endpoint Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Illustrates how to use the `@endpoint` decorator to expose a simple asynchronous Python function as an API endpoint. This example defines a GET endpoint at '/api/users/count' that returns the total number of users. ```python from jvspatial.api import endpoint from fastapi import HTTPException from typing import Dict, Any, List # Simple function endpoint @endpoint("/api/users/count", methods=["GET"]) async def get_user_count() -> Dict[str, int]: """Get total count of users in the system.""" users = await User.all() return {"total_users": len(users)} ``` -------------------------------- ### API Endpoint with Pagination and Filtering Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Shows how to implement a paginated API endpoint using the `ObjectPager` utility. This example defines a GET endpoint '/api/users/paginated' that allows filtering by department and active status, with configurable page size and page number. ```python # Function endpoint with pagination integration @endpoint("/api/users/paginated", methods=["GET"]) async def get_users_paginated( page: int = 1, page_size: int = 20, department: Optional[str] = None, active_only: bool = True ) -> Dict[str, Any]: """Get paginated list of users with filtering.""" from jvspatial.core.pager import ObjectPager # Build filters filters = {} if department: filters["context.department"] = department if active_only: filters["context.active"] = True # Create pager pager = ObjectPager( User, page_size=page_size, filters=filters, order_by="name", order_direction="asc" ) # Get page data users = await pager.get_page(page) pagination_info = pager.to_dict() return { "users": [ { "id": user.id, "name": user.name, "email": user.email, "department": user.department, "active": user.active } for user in users ], "pagination": pagination_info } ``` -------------------------------- ### Basic Webhook Handler Setup with JVspatial Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Demonstrates how to set up a simple webhook handler using JVspatial's `@endpoint` decorator. This example shows automatic JSON parsing of the payload and returning a processed response. It requires the `jvspatial.api` module. ```python from jvspatial.api import endpoint from jvspatial.api import Server # Simple webhook handler @endpoint("/webhook/payment", webhook=True) async def payment_webhook(payload: dict, endpoint): """Process payment webhooks with automatic JSON parsing.""" payment_id = payload.get("payment_id") amount = payload.get("amount") # Process payment logic here print(f"Processing payment {payment_id}: ${amount}") return endpoint.response( content={ "status": "processed", "message": f"Payment {payment_id} processed successfully" } ) # Server automatically detects and configures webhook middleware server = Server(title="My Webhook API") server.run() # Webhooks ready at /webhook/* paths ``` -------------------------------- ### Run Storage Examples Source: https://github.com/tharickv75/jvspatial_/blob/dev/examples/storage/README.md Provides commands to execute the comprehensive and basic file storage example scripts. These scripts demonstrate the practical application of jvspatial's storage features. ```bash # Run comprehensive storage example python storage_example.py # Run basic file operations demo python file_storage_demo.py ``` -------------------------------- ### Startup Hooks for Initialization Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md Shows how to use startup hooks to perform initialization tasks when the server starts. ```APIDOC ## Best Practices ### 5. Use Startup Hooks for Initialization ```python @server.on_startup async def initialize_data(): """Initialize database with required data.""" # Check if admin user exists admin = await User.get("admin") if not admin: admin = await User.create( id="admin", name="Administrator", role="admin" ) print("Created admin user") ``` **Description:** Uses the `@server.on_startup` decorator to define asynchronous functions that run once when the server begins, useful for tasks like database seeding or initial setup. ``` -------------------------------- ### API Endpoint with Path Parameters Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Shows how to define an API endpoint that accepts path parameters. This example uses `@endpoint` to create a GET endpoint '/api/cities/{state}' which retrieves cities based on the provided state and handles cases where no cities are found by raising an HTTPException. ```python # Function endpoint with path parameters @endpoint("/api/cities/{state}", methods=["GET"]) async def get_cities_by_state(state: str) -> Dict[str, Any]: """Get all cities in a specific state.""" cities = await City.find({"context.state": state}) if not cities: raise HTTPException( status_code=404, detail=f"No cities found in state: {state}" ) return { "state": state, "cities": [ { "name": city.name, "population": city.population } for city in cities ], "total_count": len(cities) } ``` -------------------------------- ### Perform Entity Operations (Create, Get, Update, Delete) (Python) Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Provides examples of common entity operations in jvspatial, including creating, retrieving, updating, and deleting entities. It highlights the automatic caching for entity retrieval by ID and the requirement for `save()` after property modifications. ```python # Entity creation (no save() needed, automatically cached) entity = await Entity.create(name="value", field="data") # Entity retrieval (uses cache after first access) entity = await Entity.get(entity_id) # Cached by ID entities = await Entity.find({"context.active": True}) # Not cached # Entity updates (save() only needed after property modification, updates cache) entity = await Entity.get(entity_id) entity.name = "Updated Name" # Property modified await entity.save() # save() required to persist changes + update cache # Entity deletion (removes from cache) await entity.delete() # Counting and aggregation (not cached) # Note: Object.count() doesn't exist - use len() with find() instead results = await Entity.find({"context.department": "engineering"}) count = len(results) # For distinct values, query and extract manually all_entities = await Entity.find({}) departments = set(e.department for e in all_entities if hasattr(e, 'department')) ``` -------------------------------- ### Authentication Setup Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/authentication.md Instructions for setting up authentication middleware and decorators. ```APIDOC # Setting Up Authentication ### Step 1: Configure authentication ```python configure_auth(jwt_secret_key="your-secret-key") ``` ### Step 2: Add middleware ```python server.app.add_middleware(AuthenticationMiddleware) ``` ### Step 3: Use endpoint decorators with auth parameters - Public endpoints: `@endpoint("/path")` - no auth required - Protected endpoints: `@endpoint("/path", auth=True)` - requires authentication - Admin endpoints: `@endpoint("/path", auth=True, roles=["admin"])` - requires admin role ``` -------------------------------- ### API Usage Examples Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Examples demonstrating how to interact with jvspatial API endpoints using curl. ```APIDOC ## API Usage Examples Once your server is running, endpoints are automatically available: ### Example: Walker Endpoint - POST Request ```bash # Walker endpoint - POST request with parameters curl -X POST "http://localhost:8000/api/users/process" \ -H "Content-Type: application/json" \ -d '{ "user_name": "John Doe", "department": "engineering", "include_inactive": false, "max_connections": 5, "start_node": "n:Root:root" }' ``` ### Example: Function Endpoint - GET Request ```bash # Function endpoint - GET request curl "http://localhost:8000/api/users/count" ``` ### Example: Function Endpoint with Path Parameters ```bash # Function endpoint with path parameters curl "http://localhost:8000/api/cities/CA" ``` ### Example: Function Endpoint with Query Parameters ```bash # Function endpoint with query parameters curl "http://localhost:8000/api/users/paginated?page=1&page_size=10&department=engineering" ``` **API Documentation Access:** - http://localhost:8000/docs (Swagger UI) - http://localhost:8000/redoc (ReDoc) ``` -------------------------------- ### Endpoint Security with Permissions and Roles Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/auth-quickstart.md Demonstrates how to secure API endpoints using the @endpoint decorator with specific permissions and roles. This ensures that only authorized users or roles can access certain functionalities. ```python from jvspatial.api import endpoint # Require specific permissions @endpoint("/reports", auth=True, permissions=["read_reports"]) async def get_reports(): return {"reports": ["Monthly", "Weekly"]} # Require specific roles @endpoint("/analyze", auth=True, roles=["analyst", "admin"]) async def analyze_data(): return {"analysis": "Complex analysis results"} # Multiple requirements @endpoint("/advanced", auth=True, permissions=["advanced_ops"], roles=["admin"]) async def advanced_ops(): return {"message": "Advanced operations"} ``` -------------------------------- ### Implement Custom Storage Provider in Python Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/file-storage-usage.md Provides a detailed example of creating a custom file storage provider by inheriting from `FileStorageInterface`. This includes implementing methods for saving, retrieving, streaming, deleting, checking existence, getting info, and generating signed URLs. It also shows how to register and use the custom provider. ```python from jvspatial.storage.interfaces import FileStorageInterface from typing import AsyncIterator, Optional, Dict, Any class CustomStorageProvider(FileStorageInterface): """Custom storage provider implementation.""" def __init__(self, **config): self.config = config # Initialize your storage backend async def save_file( self, file_path: str, content: bytes, metadata: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """Save file to custom storage.""" # Your implementation return { "path": file_path, "size": len(content), "checksum": self._calculate_checksum(content) } async def get_file(self, file_path: str) -> Optional[bytes]: """Retrieve file from custom storage.""" # Your implementation pass async def stream_file( self, file_path: str ) -> AsyncIterator[bytes]: """Stream file from custom storage.""" chunk_size = 1048576 # 1MB # Yield chunks pass async def delete_file(self, file_path: str) -> bool: """Delete file from custom storage.""" # Your implementation pass async def file_exists(self, file_path: str) -> bool: """Check if file exists.""" # Your implementation pass async def get_file_info( self, file_path: str ) -> Optional[Dict[str, Any]]: """Get file metadata.""" # Your implementation pass async def get_signed_url( self, file_path: str, expires_in: int = 3600 ) -> Optional[str]: """Generate signed URL (if supported).""" # Your implementation or return None return None def _calculate_checksum(self, content: bytes) -> str: """Calculate file checksum.""" import hashlib return hashlib.sha256(content).hexdigest() # Register custom provider from jvspatial.storage.interfaces.factory import register_provider register_provider("custom", CustomStorageProvider) # Use custom provider server = Server( file_storage_enabled=True, file_storage_provider="custom", file_storage_custom_config={ "endpoint": "https://custom-storage.example.com", "api_key": "your-api-key" } ) ``` -------------------------------- ### Basic Configuration Example Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md Demonstrates how to configure the jvspatial Server with basic settings like title, description, version, host, port, and debug mode. ```APIDOC ## Configuration ### Basic Configuration **Description**: Example showing basic server configuration parameters. ### Code Example ```python from jvspatial.api.server import Server server = Server( title="My API", description="API description", version="1.0.0", host="0.0.0.0", port=8000, debug=False ) ``` ``` -------------------------------- ### Python API Server with Scheduler Integration using jvspatial Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Integrates the `jvspatial.api.Server` with `jvspatial.core.scheduler.Scheduler`. This setup allows for running scheduled tasks alongside the API server. Startup and shutdown hooks (`on_startup`, `on_shutdown`) are used to manage the scheduler's lifecycle, ensuring it starts when the server begins and stops gracefully when the server is shut down. ```python from jvspatial.api import Server from jvspatial.core.scheduler import Scheduler from datetime import timedelta # Create integrated server with scheduler server = Server(title="Scheduled API", port=8000) scheduler = Scheduler() # Add scheduled tasks @scheduler.task(interval=timedelta(minutes=5)) async def periodic_health_check(): """Check system health every 5 minutes.""" # Health check logic here pass @server.on_startup async def startup_tasks(): """Start scheduler when server starts.""" await scheduler.start() print("✅ Server and scheduler started") @server.on_shutdown async def shutdown_tasks(): """Stop scheduler when server shuts down.""" await scheduler.stop() print("🛑 Server and scheduler stopped") # Run integrated server if __name__ == "__main__": server.run() ``` -------------------------------- ### Basic Server Implementation (Python) Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md Presents a minimal example of setting up and running a jvspatial API server. It shows the instantiation of the `Server` class with basic configuration and defines a simple Walker endpoint, followed by running the server using `server.run()`. ```python from jvspatial.api import Server, endpoint server = Server( title="My API", db_type="json", db_path="./jvdb" ) @endpoint("/process", methods=["POST"]) class ProcessData(Walker): # Walker implementation pass if __name__ == "__main__": server.run() ``` -------------------------------- ### Simple Webhook Setup Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Illustrates a basic webhook handler for processing payment notifications with automatic JSON parsing. ```APIDOC ## POST /webhook/payment ### Description Processes payment webhooks. The system automatically parses the JSON payload, making it easy to access payment details. ### Method POST ### Endpoint `/webhook/payment` ### Parameters #### Query Parameters (None specified) #### Request Body - **payload** (dict) - Required - Contains payment details such as `payment_id` and `amount`. ### Request Example ```json { "payment_id": "pay_12345", "amount": 100.50 } ``` ### Response #### Success Response (200) - **status** (string) - Confirmation of successful processing. - **message** (string) - A descriptive message about the payment processing. #### Response Example ```json { "status": "processed", "message": "Payment pay_12345 processed successfully" } ``` ``` -------------------------------- ### Startup Hooks for Initialization (Python) Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md Illustrates how to use the `@server.on_startup` decorator to define asynchronous functions that run once when the server starts. This is useful for tasks like initializing the database, seeding data, or setting up essential configurations before the server begins accepting requests. ```python @server.on_startup async def initialize_data(): """Initialize database with required data.""" # Check if admin user exists admin = await User.get("admin") if not admin: admin = await User.create( id="admin", name="Administrator", role="admin" ) print("Created admin user") ``` -------------------------------- ### JVspatial Anti-Patterns: Relative Imports in Examples Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/import-patterns.md Discourages the use of relative imports within code examples and promotes absolute imports for clarity and maintainability. ```python # ❌ Bad: Relative imports in your code from ..core import Node from ...api import Server # ✅ Good: Absolute imports from jvspatial.core import Node from jvspatial.api import Server ``` -------------------------------- ### Basic and Advanced Server Setup with FastAPI Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Demonstrates how to set up a basic and an advanced FastAPI server using the jvspatial Server and ServerConfig classes. Covers essential parameters like title, description, host, port, and debug mode, as well as advanced configurations for database connections, CORS, and API documentation URLs. ```python from jvspatial.api import Server, ServerConfig, endpoint, walker_endpoint from jvspatial.api.endpoint.router import EndpointField from jvspatial.core import Node, Walker from jvspatial.core.entities import on_visit # Basic server setup server = Server( title="My Spatial API", description="Graph-based spatial data management API", version="1.0.0", host="0.0.0.0", port=8000, debug=True # Enable for development ) # Advanced server configuration advanced_config = ServerConfig( title="Production Spatial API", description="Enterprise graph data API", version="2.0.0", host="0.0.0.0", port=8080, # Database configuration db_type="mongodb", db_connection_string="mongodb://localhost:27017", db_database_name="spatial_db", # CORS settings cors_enabled=True, cors_origins=["https://myapp.com", "http://localhost:3000"], # API documentation docs_url="/api/docs", redoc_url="/api/redoc", log_level="info" ) production_server = Server(config=advanced_config) ``` -------------------------------- ### Running the Server Source: https://github.com/tharickv75/jvspatial_/blob/dev/docs/md/server-api.md Provides a basic example of how to run the jvspatial server. ```APIDOC ## Server Class Benefits ```python from jvspatial.api import Server, endpoint server = Server( title="My API", db_type="json", db_path="./jvdb" ) @endpoint("/process", methods=["POST"]) class ProcessData(Walker): # Walker implementation pass if __name__ == "__main__": server.run() ``` **Description:** A minimal example demonstrating server instantiation, endpoint definition, and how to start the server using `server.run()`. ``` -------------------------------- ### GET /api/export Source: https://github.com/tharickv75/jvspatial_/blob/dev/SPEC.md Exports data in a specified format. ```APIDOC ## GET /api/export ### Description Exports data in a specified format (JSON, CSV, or XML). Handles unsupported formats. ### Method GET ### Endpoint /api/export ### Parameters #### Path Parameters None #### Query Parameters - **format** (string) - Required - The desired export format ('json', 'csv', or 'xml'). #### Request Body None ### Request Example ```json ?format=json ``` ### Response #### Success Response (200 OK) - **data** (object) - Exported data (structure depends on format). - **message** (string) - A success message. #### Error Response (406 Not Acceptable) - **message** (string) - Error message indicating an unsupported export format. - **details** (object) - Additional error details, including the provided and supported formats. #### Response Example (Unsupported Format) ```json { "message": "Unsupported export format", "status_code": 406, "details": { "format": "pdf", "supported": ["json", "csv", "xml"] } } ``` ```