Aller au contenu principal

Python SDK

Official Python SDK for ArchiCore API.

Installation

pip install archicore

Requirements

  • Python 3.8+
  • requests library (installed automatically)

Quick Start

from archicore import ArchiCore

client = ArchiCore(api_key="your-api-key")

# List all projects
projects = client.projects.list()
print(projects)

Configuration

client = ArchiCore(
api_key="your-api-key", # Required
base_url="https://api.archicore.io/api/v1", # Optional
timeout=30, # Optional, in seconds
)

Environment Variables

import os
from archicore import ArchiCore

client = ArchiCore(api_key=os.environ["ARCHICORE_API_KEY"])

Projects

List Projects

projects = client.projects.list()
for project in projects:
print(f"{project['name']} - {project['status']}")

Get Project

project = client.projects.get("project-id")
print(project["name"])
print(project["stats"]["files"])

Create Project

project = client.projects.create(
name="my-project",
source="/path/to/project", # Optional
github_url="https://github.com/...", # Optional
)

Delete Project

client.projects.delete("project-id")

Index Project

status = client.projects.index("project-id", force=True)
print(status["status"])
results = client.projects.search(
"project-id",
query="authentication middleware",
limit=10, # Optional
threshold=0.7, # Optional
)

for result in results:
print(f"{result['file']}:{result['line']} ({result['score']:.2f})")
print(result['code'])

AI Assistant

Ask Questions

answer = client.projects.ask(
"project-id",
question="How does the authentication system work?",
context="Focus on JWT implementation", # Optional
)

print(answer["response"])

if answer.get("sources"):
print("\nSources:")
for source in answer["sources"]:
print(f" {source['file']}:{source['line']}")

Metrics

Get Project Metrics

metrics = client.projects.metrics("project-id")

print(f"Files: {metrics['totalFiles']}")
print(f"Lines: {metrics['totalLines']}")
print(f"Complexity: {metrics.get('complexity', {}).get('average', 'N/A')}")

print("\nLanguages:")
for lang, count in metrics.get("languages", {}).items():
print(f" {lang}: {count}")

Security

Get Security Report

report = client.projects.security("project-id")

summary = report["summary"]
print(f"Critical: {summary['critical']}")
print(f"High: {summary['high']}")
print(f"Medium: {summary['medium']}")
print(f"Low: {summary['low']}")

for vuln in report["vulnerabilities"]:
print(f"[{vuln['severity'].upper()}] {vuln['type']}")
print(f" {vuln['message']}")
print(f" {vuln['file']}:{vuln['line']}")

Impact Analysis

Analyze Changes

impact = client.projects.analyze(
"project-id",
files=["src/auth/login.ts", "src/auth/session.ts"],
)

print(f"Risk Level: {impact['riskLevel']}")
print(f"Affected Files: {len(impact['affectedFiles'])}")

for file in impact["affectedFiles"][:5]:
print(f" - {file}")

if impact.get("suggestions"):
print("\nSuggestions:")
for suggestion in impact["suggestions"]:
print(f" - {suggestion}")

Enterprise Analysis

For large projects with 50K+ files.

Get Estimate

estimate = client.projects.enterprise_estimate("project-id")

print(f"Total files: {estimate['totalFiles']:,}")
print(f"Project size: {estimate['totalSizeMB']:.1f} MB")
print(f"Recommended tier: {estimate['recommendation'].upper()}")

print("\nLanguage Distribution:")
for lang, count in sorted(
estimate["languageDistribution"].items(),
key=lambda x: x[1],
reverse=True
)[:5]:
print(f" {lang}: {count:,}")

Start Enterprise Indexing

# Quick analysis with smart sampling
task = client.projects.enterprise_index(
"project-id",
tier="quick",
sampling_strategy="smart"
)
print(f"Task ID: {task['taskId']}")

# Standard with focus directories
task = client.projects.enterprise_index(
"project-id",
tier="standard",
sampling_strategy="hot-files",
focus_directories=["src/core", "src/api"],
exclude_patterns=["test", "spec", "__pycache__"]
)

# Incremental indexing
task = client.projects.enterprise_index(
"project-id",
tier="standard",
incremental_since="2024-01-01" # or git commit hash
)

Preview Files

preview = client.projects.enterprise_files_preview(
"project-id",
tier="standard",
strategy="smart"
)

print(f"Would analyze {preview['totalSelected']:,} of {preview['maxAllowed']:,} files")
print("\nSample files:")
for file in preview["files"][:10]:
print(f" {file}")

Check Incremental Changes

# Since date
changes = client.projects.enterprise_incremental(
"project-id",
since="2024-01-01"
)

# Since commit hash
changes = client.projects.enterprise_incremental(
"project-id",
since="abc123f"
)

print(f"Changed files: {changes['changedFiles']}")
for file in changes["files"][:10]:
print(f" {file}")

Webhooks

List Webhooks

webhooks = client.webhooks.list()
for webhook in webhooks:
print(f"{webhook['id']}: {webhook['url']}")
print(f" Events: {', '.join(webhook['events'])}")

Create Webhook

webhook = client.webhooks.create(
url="https://your-server.com/webhook",
events=["project.indexed", "analysis.complete"],
project_id="project-id", # Optional
secret="webhook-secret", # Optional
)
print(f"Created webhook: {webhook['id']}")

Delete Webhook

client.webhooks.delete("webhook-id")

Error Handling

from archicore import ArchiCore
from archicore.exceptions import (
ArchiCoreError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError,
ServerError
)

client = ArchiCore(api_key="your-api-key")

try:
project = client.projects.get("project-id")
except AuthenticationError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limited. Retry after {e.retry_after}s")
print(f"Limit: {e.limit}, Remaining: {e.remaining}")
except NotFoundError:
print("Project not found")
except ValidationError as e:
print(f"Invalid request: {e}")
except ServerError:
print("Server error, try again later")
except ArchiCoreError as e:
print(f"API error: {e} (code: {e.code})")

Context Manager

The client can be used as a context manager:

with ArchiCore(api_key="your-api-key") as client:
projects = client.projects.list()
# Session is automatically closed

Examples

Daily Security Scan

#!/usr/bin/env python3
"""Daily security scan script."""

import os
import sys
from archicore import ArchiCore

def main():
client = ArchiCore(api_key=os.environ["ARCHICORE_API_KEY"])

for project in client.projects.list():
print(f"\n=== {project['name']} ===")

report = client.projects.security(project["id"])
summary = report["summary"]

if summary["critical"] > 0:
print(f" CRITICAL: {summary['critical']} issues!")
sys.exit(1)

if summary["high"] > 0:
print(f" HIGH: {summary['high']} issues")

print(f" Medium: {summary['medium']}, Low: {summary['low']}")

if __name__ == "__main__":
main()

CI/CD Integration

#!/usr/bin/env python3
"""GitHub Actions integration."""

import os
import sys
from archicore import ArchiCore

def analyze_pr():
client = ArchiCore(api_key=os.environ["ARCHICORE_API_KEY"])
project_id = os.environ["ARCHICORE_PROJECT_ID"]

# Get changed files from environment
changed_files = os.environ.get("CHANGED_FILES", "").split(",")
changed_files = [f.strip() for f in changed_files if f.strip()]

if not changed_files:
print("No changed files")
return

# Impact analysis
impact = client.projects.analyze(project_id, files=changed_files)

print(f"Risk Level: {impact['riskLevel']}")
print(f"Affected: {len(impact['affectedFiles'])} files")

if impact["riskLevel"] == "high":
print("::warning::High impact changes detected")
for suggestion in impact.get("suggestions", []):
print(f" - {suggestion}")

# Security check
security = client.projects.security(project_id)
if security["summary"]["critical"] > 0:
print("::error::Critical security issues found")
sys.exit(1)

if __name__ == "__main__":
analyze_pr()

Slack Bot

from flask import Flask, request, jsonify
from archicore import ArchiCore
import os

app = Flask(__name__)
client = ArchiCore(api_key=os.environ["ARCHICORE_API_KEY"])

@app.route("/slack/ask", methods=["POST"])
def slack_ask():
data = request.form
question = data.get("text", "")
project_id = os.environ["DEFAULT_PROJECT_ID"]

answer = client.projects.ask(project_id, question=question)

return jsonify({
"response_type": "in_channel",
"text": answer["response"]
})

if __name__ == "__main__":
app.run(port=3000)

Batch Analysis

"""Analyze multiple projects in parallel."""

import os
from concurrent.futures import ThreadPoolExecutor
from archicore import ArchiCore

def analyze_project(client, project):
metrics = client.projects.metrics(project["id"])
security = client.projects.security(project["id"])

return {
"name": project["name"],
"files": metrics["totalFiles"],
"lines": metrics["totalLines"],
"vulnerabilities": len(security["vulnerabilities"]),
"critical": security["summary"]["critical"],
}

def main():
client = ArchiCore(api_key=os.environ["ARCHICORE_API_KEY"])
projects = client.projects.list()

with ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(
lambda p: analyze_project(client, p),
projects
))

# Print summary
print(f"{'Project':<30} {'Files':>10} {'Lines':>10} {'Vulns':>6} {'Critical':>8}")
print("-" * 70)

for r in sorted(results, key=lambda x: x["critical"], reverse=True):
print(f"{r['name']:<30} {r['files']:>10,} {r['lines']:>10,} {r['vulnerabilities']:>6} {r['critical']:>8}")

if __name__ == "__main__":
main()