Skip to content

FastAPI Server Reference

What this page is: Reference for COGANT's packaged/demo FastAPI application (cogant.server.app) and all 11 exposed HTTP routes.

Prerequisites: Installation and familiarity with the analysis pipeline.

Reading time: ~10 minutes

Next steps: Complete Example · API Stability · Performance Tips

Overview

cogant.server.app exposes a FastAPI application for analyzing codebases and operating the reverse pipeline via HTTP. The server provides JSON endpoints for translation, reverse synthesis, roundtrip validation, and metrics retrieval. It is packaged as a runnable demo/container surface (cogant/Dockerfile, docker-compose.yml) and can also be started directly from Python. It is not a turnkey internet-facing service: token authentication, TLS termination, stricter CORS, and reverse-proxy policy are caller-owned.

Routes

Method Path Description Request Response
GET /health Service health check none {"status": "ok", "version": "..."}
GET /ready Readiness probe with dependency checks none {"ready": bool, "checks": {...}}
GET /metrics Prometheus-format text metrics none Plain text (Prometheus format)
POST /analyze Full translation pipeline {"repo_path": str, "config"?: {...}} GNN bundle JSON
POST /reverse GNN-to-code synthesis {"gnn_text": str} {"package_zip_b64": str, "file_count": int, "cogant_version": str}
POST /roundtrip Forward-then-reverse validation {"repo_path": str} {"isomorphism_score": float, "result": str}
GET /api/v1/rules List all active translation rules none [{"name": str, "family": str, "priority": int}, ...]
POST /api/v1/analyze Alias for /analyze {"repo_path": str, "config"?: {...}} GNN bundle JSON
POST /api/v1/roundtrip Alias for /roundtrip {"repo_path": str} {"isomorphism_score": float, "result": str}
POST /api/v1/visualize Generate graph visualizations {"gnn_bundle": {...}} {"svg": str, "mermaid": str}
GET /api/v1/metrics Structured JSON metrics none {"rule_counts": {...}, "graph_size": {...}, ...}

Request/Response Details

POST /analyze

Request:

{
  "repo_path": "/path/to/repo",
  "config": {
    "output_dir": "output/",
    "no_dynamic": false,
    "min_confidence": 0.4,
    "markov_seed": "auto"
  }
}

Response: Full GNN bundle as JSON (same format as cogant translate --output).

POST /reverse

Request:

{
  "gnn_text": "# GNN\n[HIDDEN_STATE x]\n..."
}

Response: The synthesized Python package returned as a base64-encoded zip plus a small metadata envelope.

{
  "package_zip_b64": "UEsDBBQAAAAIAA...",
  "file_count": 6,
  "cogant_version": "0.8.0"
}

package_zip_b64 decodes to a standard zip containing the same module layout cogant.reverse.synthesizer.synthesize_package would write to disk. file_count is the number of files inside the zip (driver helpers + per-state / per-action / per-observation modules).

GET /api/v1/rules

Response:

[
  {"name": "MutatingSubsystemRule", "family": "structural", "priority": 10},
  {"name": "ActionRule", "family": "semantic", "priority": 15},
  ...
]

POST /api/v1/visualize

Request:

{
  "gnn_bundle": { ... },
  "options": {
    "show_confidence": true,
    "highlight_low_confidence": false
  }
}

Response:

{
  "svg": "<svg>...</svg>",
  "mermaid": "graph TD; ...",
  "json_format": "..."
}

Starting the Server

Python (Direct)

from cogant.server.app import create_app
import uvicorn

app = create_app()
uvicorn.run(app, host="0.0.0.0", port=8080, workers=1)

Docker

The build context must be the package root (the directory holding Dockerfile, pyproject.toml, and uv.lock); the image installs the committed lockfile with uv sync --frozen --no-dev and fails fast if it is missing.

# Build image (from the repository root; use `.` when already inside cogant/)
docker build -t cogant:latest cogant/

# Run container
docker run -p 8080:8080 \
  -e COGANT_RATE_LIMIT=100 \
  -e LOG_LEVEL=info \
  cogant:latest

Docker Compose

# From the repository root (or drop -f when already inside cogant/)
docker compose -f cogant/docker-compose.yml up --build

# Logs (the compose service is named `cogant`)
docker compose -f cogant/docker-compose.yml logs -f cogant

The docker-compose.yml exposes port 8080 and sets standard logging.

Configuration

Server behavior is controlled via environment variables:

Variable Default Purpose
COGANT_RATE_LIMIT 100 Requests per minute per IP (middleware rate limiter)
COGANT_TIMEOUT 300 Request timeout in seconds
COGANT_MAX_WORKERS 4 Number of uvicorn worker processes
COGANT_LOG_LEVEL "info" Log level (debug, info, warning, error)
COGANT_CORS_ORIGINS ["*"] CORS allowed origins (comma-separated or JSON list)

Authentication & Security

The packaged server binds to loopback by default. Configuring a non-loopback bind requires an authentication token. When a token is configured, non-public routes require an Authorization: Bearer ... header. This is a local analysis service, not a sandbox for arbitrary code. The application also implements:

  • Rate limiting (configurable via COGANT_RATE_LIMIT env var): 100 requests/minute per IP by default.
  • CORS middleware (default: all origins allowed; tighten via COGANT_CORS_ORIGINS).
  • Request timeouts (configurable via COGANT_TIMEOUT).

For production-like deployments, place the server behind a reverse proxy (nginx, Envoy, or equivalent) with API key or identity enforcement, TLS termination, request-size limits, and stricter CORS policies before exposing it outside a trusted network.

Error Responses

All endpoints return JSON errors in this format:

{
  "detail": "Human-readable error message",
  "status": 400,
  "error_code": "INVALID_REPO_PATH"
}

Common error codes:

  • INVALID_REPO_PATH — repo_path does not exist or is not readable
  • PARSE_ERROR — Python/JS/TS parsing failed (syntax error or unsupported grammar)
  • TRANSLATION_FAILED — GNN translation did not produce valid mappings
  • VALIDATION_FAILED — Output bundle failed validation checks
  • TIMEOUT — Request exceeded COGANT_TIMEOUT threshold

Health Checks

/health

Lightweight check; always returns 200 if the server is running.

curl http://localhost:8080/health
# {"status": "ok", "version": "..."}

/ready

Detailed readiness; returns 503 if dependencies are missing or misconfigured.

curl http://localhost:8080/ready
# {
#   "ready": true,
#   "checks": {
#     "python_parser": "ok",
#     "tree_sitter": "ok",
#     "rust_backend": "unavailable"
#   }
# }

Metrics

GET /metrics (Prometheus format)

# TYPE cogant_analysis_total counter
cogant_analysis_total{status="success"} 42
# TYPE cogant_analysis_duration_seconds histogram
cogant_analysis_duration_seconds_bucket{le="1.0"} 10

GET /api/v1/metrics (JSON)

{
  "total_analyses": 42,
  "successful_analyses": 40,
  "failed_analyses": 2,
  "mean_duration_seconds": 2.3,
  "rule_counts": {
    "MutatingSubsystemRule": 156,
    "ActionRule": 89,
    ...
  }
}

Examples

Analyze a repository

curl -X POST http://localhost:8080/analyze \
  -H "Content-Type: application/json" \
  -d '{"repo_path": "/path/to/repo", "config": {"no_dynamic": true}}'

Reverse a GNN

curl -X POST http://localhost:8080/reverse \
  -H "Content-Type: application/json" \
  -d '{"gnn_text": "# GNN\n[HIDDEN_STATE x]\n..."}'

Get active rules

curl http://localhost:8080/api/v1/rules | jq '.[] | .name'

Generate visualizations

curl -X POST http://localhost:8080/api/v1/visualize \
  -H "Content-Type: application/json" \
  -d '{"gnn_bundle": {...}}'

See Also