Python Examples for adaline.report
Complete Python code examples for the Adaline Report API using the requests library.
All examples use the requests library. Install with pip install requests.
Setup
import requests
API_KEY = "your-api-key"
BASE_URL = "https://api.adaline.report"
headers = {
"X-API-Key": API_KEY,
}
Scan a Document
def scan_document(file_path, tiers=None):
"""Upload and scan a document for accessibility compliance."""
with open(file_path, "rb") as f:
files = {"file": f}
data = {"tiers": tiers} if tiers else {}
response = requests.post(
f"{BASE_URL}/api/v1/scan",
headers=headers,
files=files,
data=data,
)
response.raise_for_status()
return response.json()
result = scan_document("syllabus.pdf")
print(f"Score: {result['overall_score']}% (Grade {result['grade']})")
print(f"Compliant: {result['compliant']}")
print(f"Passed: {result['total_passed']}/{result['total_checks']} checks")
List Reports
def list_reports(page=1, page_size=20):
"""List all compliance reports with pagination."""
response = requests.get(
f"{BASE_URL}/api/v1/reports",
headers=headers,
params={"page": page, "page_size": page_size},
)
response.raise_for_status()
return response.json()
data = list_reports()
for report in data["items"]:
print(f"{report['filename']}: {report['overall_score']}% ({report['grade']})")
Get Report Details
def get_report(report_id):
"""Get a specific report with full check details."""
response = requests.get(
f"{BASE_URL}/api/v1/reports/{report_id}",
headers=headers,
)
response.raise_for_status()
return response.json()
report = get_report("your-report-id")
# Print category scores
for name, cat in report["categories"].items():
print(f" {name}: {cat['score']}% ({cat['passed']}/{cat['total']} passed)")
# Print failed checks
for check in report["checks"]:
if not check["passed"]:
print(f" [{check['severity']}] {check['details']}")
Batch Scan Multiple Documents
import os
from pathlib import Path
def batch_scan(directory, extensions=(".pdf", ".docx", ".pptx")):
"""Scan all documents in a directory."""
results = []
for file_path in Path(directory).iterdir():
if file_path.suffix.lower() in extensions:
print(f"Scanning {file_path.name}...")
try:
result = scan_document(str(file_path))
results.append({
"file": file_path.name,
"score": result["overall_score"],
"grade": result["grade"],
"report_id": result["report_id"],
})
except requests.HTTPError as e:
results.append({
"file": file_path.name,
"error": str(e),
})
return results
results = batch_scan("./course-materials")
for r in results:
if "error" in r:
print(f" {r['file']}: FAILED - {r['error']}")
else:
print(f" {r['file']}: {r['score']}% ({r['grade']})")
Tags
def create_tag(name, color=None):
"""Create a new tag."""
body = {"name": name}
if color:
body["color"] = color
response = requests.post(
f"{BASE_URL}/api/v1/tags",
headers={**headers, "Content-Type": "application/json"},
json=body,
)
response.raise_for_status()
return response.json()
def tag_report(tag_id, report_id):
"""Add a tag to a report."""
response = requests.post(
f"{BASE_URL}/api/v1/tags/{tag_id}/reports/{report_id}",
headers=headers,
)
response.raise_for_status()
# Create a tag and apply it
tag = create_tag("needs-review", "red")
tag_report(tag["id"], "your-report-id")
Share a Report
def share_report(report_id):
"""Create a public share link for a report."""
response = requests.post(
f"{BASE_URL}/api/v1/reports/{report_id}/share",
headers=headers,
)
response.raise_for_status()
return response.json()
share = share_report("your-report-id")
print(f"Share URL: {share['share_url']}")
Error Handling
def safe_scan(file_path):
"""Scan with proper error handling."""
try:
result = scan_document(file_path)
return result
except requests.HTTPError as e:
if e.response.status_code == 401:
print("Invalid API key. Check your X-API-Key header.")
elif e.response.status_code == 400:
detail = e.response.json().get("detail", "Unknown error")
print(f"Bad request: {detail}")
elif e.response.status_code == 429:
print("Rate limited. Wait a moment and try again.")
else:
print(f"API error {e.response.status_code}: {e.response.text}")
return None
except requests.ConnectionError:
print("Could not connect to the API. Check your network.")
return None
Full Workflow Example
def compliance_workflow(file_path):
"""Complete workflow: scan, check results, tag, and share."""
# 1. Scan the document
print(f"Scanning {file_path}...")
result = scan_document(file_path)
report_id = result["report_id"]
score = result["overall_score"]
grade = result["grade"]
print(f"Score: {score}% (Grade {grade})")
# 2. Check for critical failures
critical_failures = [
c for c in result["checks"]
if not c["passed"] and c["severity"] == "critical"
]
if critical_failures:
print(f"\n{len(critical_failures)} critical issue(s):")
for check in critical_failures:
print(f" - {check['details']}")
# 3. Tag based on result
if result["compliant"]:
tag = create_tag("compliant", "green")
elif score >= 70:
tag = create_tag("needs-fixes", "yellow")
else:
tag = create_tag("non-compliant", "red")
tag_report(tag["id"], report_id)
# 4. Share the report
share = share_report(report_id)
print(f"\nReport: {share['share_url']}")
return result
compliance_workflow("quarterly-report.pdf")