Semantica API: How to Interact with the Knowledge Graph via REST Endpoints

Semantica provides a full-featured REST API built on FastAPI, with core endpoints always available and an extended Explorer API available as an optional dependency.

The semantica-agi/semantica repository exposes programmatic HTTP access to its knowledge graph engine through a modular FastAPI architecture. Understanding the Semantica API structure lets you automate knowledge base construction, execute graph queries, and integrate semantic reasoning into external applications.

Core API: Always Available Endpoints

The foundation of the Semantica API resides in semantica/server.py, which instantiates the FastAPI application and registers three essential routes regardless of optional dependencies.

Framework Metadata

Endpoint Method Purpose
/api/info GET Returns framework name, version, and status
/health GET Health-check for uptime monitoring
/build POST Initiates knowledge base construction jobs

These endpoints mount at application startup without requiring additional packages. The /build endpoint accepts a JSON payload specifying data sources and configuration options for the knowledge graph construction pipeline.

Authentication Header Structure

All API requests to protected routes require an X-API-Key header when the SEMANTICA_API_KEY environment variable is configured. The require_auth dependency in semantica/server.py (lines 42‑53) enforces this validation across the Explorer API routes.

Explorer API: Extended Graph Operations

Installing semantica[explorer] unlocks a comprehensive route tree under /api/* for advanced knowledge graph interaction. The explorer routes mount conditionally in semantica/server.py (lines 59‑86) based on import availability.

Available Explorer Route Categories

  • Graph operations (/api/graph/*) – pathfinding, node search, distance matrices, subgraph extraction
  • Analytics – statistical metrics and centrality calculations
  • Decisions – reasoning and inference endpoints
  • Ontology management – schema and taxonomy operations
  • Temporal reasoning – time-aware graph queries
  • Vocabulary lookup – term resolution and disambiguation
  • Provenance tracking – data lineage and source attribution
  • SPARQL operations – standards-compliant graph query language support

Individual route modules live in semantica/explorer/routes/ with dedicated files for each functional domain.

API Architecture Components

Understanding the file structure clarifies how requests flow through the system:

  1. semantica/server.py – Creates the root FastAPI app, configures CORS, security headers, and conditionally includes explorer routers
  2. semantica/explorer/app.py – Factory function building the explorer-specific FastAPI instance with session and WebSocket management
  3. semantica/explorer/routes/graph.py – Implements graph traversal algorithms and search operations
  4. semantica/explorer/routes/vocabulary.py – Handles term lookup and lexicon management
  5. semantica/explorer/dependencies.py – Supplies authentication helpers and configuration injection
  6. semantica/context/context_graph.py – Core knowledge graph implementation backing all API responses
  7. semantica/explorer/session.py – Per-request session state management

Practical API Usage Examples

The following Python examples demonstrate common Semantica API interactions using standard HTTP requests.

Basic Information and Health Checks

import requests

BASE = "http://localhost:8000"  # default FastAPI development server

# Retrieve framework metadata

resp = requests.get(f"{BASE}/api/info")
print(resp.json())

# {'name': 'Semantica API', 'version': 'x.y.z', 'status': 'active'}

# Verify service availability

resp = requests.get(f"{BASE}/health")
assert resp.json()["status"] == "healthy"

Knowledge Base Construction

import requests

BASE = "http://localhost:8000"

# Trigger asynchronous knowledge graph build

payload = {
    "sources": ["data/documents/", "data/structured_data.json"],
    "config": {
        "embedding_model": "openai/text-embedding-3-small",
        "chunk_size": 512
    }
}
resp = requests.post(f"{BASE}/build", json=payload)
print(resp.json())

# {'status': 'accepted', 'message': 'Knowledge base construction initiated'}

Explorer API: Graph Pathfinding

import requests

BASE = "http://localhost:8000"
API_KEY = "your-semantica-api-key"  # required when SEMANTICA_API_KEY is set

# Find shortest path between two nodes

params = {
    "source": "concept://entity/semiconductor",
    "target": "concept://entity/transistor",
    "algorithm": "bfs",
    "directed": "true",
    "max_depth": 5
}
headers = {"X-API-Key": API_KEY}

resp = requests.get(
    f"{BASE}/api/graph/path",
    params=params,
    headers=headers
)
result = resp.json()
print(f"Path length: {result['distance']}")
print(f"Nodes traversed: {result['path']}")

Explorer API: Vocabulary Resolution

import requests

BASE = "http://localhost:8000"
headers = {"X-API-Key": API_KEY}

# Resolve ambiguous terms to canonical concepts

resp = requests.post(
    f"{BASE}/api/vocabulary/resolve",
    json={
        "terms": ["bank", "java", "apple"],
        "context": "financial technology sector",
        "max_candidates": 3
    },
    headers=headers
)
print(resp.json())

# Returns ranked concept mappings with confidence scores

Request/Response Model Conventions

The Semantica API follows FastAPI standard patterns:

  • Pydantic models define all request bodies and response schemas
  • Async function handlers process requests concurrently
  • Automatic OpenAPI documentation generates at /docs when the server runs
  • Structured error responses include HTTP status codes and descriptive messages

Each explorer route module in semantica/explorer/routes/ exports a FastAPI router instance decorated with operation tags for documentation organization.

Authentication Configuration

The require_auth dependency validates bearer tokens against the SEMANTICA_API_KEY environment variable. When this variable is unset, explorer routes operate without authentication—suitable only for development environments. Production deployments must configure API key validation.

Summary

  • Semantica exposes a FastAPI-based REST API with core endpoints in semantica/server.py and extended Explorer routes available via semantica[explorer]
  • Always-available endpoints (/api/info, /health, /build) provide metadata, health checks, and knowledge base construction triggers
  • Explorer API routes under /api/* enable graph queries, analytics, reasoning, ontology management, and SPARQL operations
  • Authentication uses X-API-Key headers enforced by the require_auth dependency when SEMANTICA_API_KEY is configured
  • Request handling leverages Pydantic models, async handlers, and automatic OpenAPI schema generation per FastAPI conventions

Frequently Asked Questions

Does Semantica require authentication for all API endpoints?

Core endpoints (/api/info, /health, /build) do not require authentication. The Explorer API routes require an X-API-Key header only when the SEMANTICA_API_KEY environment variable is set. This conditional authentication, implemented in semantica/server.py lines 42‑53, lets you run development instances without credentials while securing production deployments.

What Python package do I install to access the full Explorer API?

Install semantica[explorer] to enable the extended route tree. The base semantica package provides only the core three endpoints. The explorer routes in semantica/explorer/routes/ mount conditionally based on successful import of the explorer subpackage, as handled in semantica/server.py lines 59‑86.

Can I query the knowledge graph using standard SPARQL?

Yes. The Explorer API includes SPARQL operations under the /api/* namespace when installed. This provides standards-compliant graph query language support alongside Semantica's native REST endpoints for pathfinding, analytics, and reasoning operations.

How does the Semantica API handle concurrent requests?

The API uses FastAPI's async request handlers and Starlette's ASGI server for concurrent request processing. Per-request session state management in semantica/explorer/session.py ensures isolated execution contexts for overlapping operations against the shared knowledge graph in semantica/context/context_graph.py.

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:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →