Python Examples for adaline.ink
Complete Python code examples for the Adaline platform API using the requests library.
All examples use the requests library. Install with pip install requests.
Setup
import requests
BASE_URL = "https://api.adaline.ink"
def login(email, password):
"""Authenticate and return an access token."""
res = requests.post(f"{BASE_URL}/api/v1/auth/login", json={
"email": email,
"password": password,
})
res.raise_for_status()
data = res.json()
return data["access_token"], data["refresh_token"]
access_token, refresh_token = login("you@example.com", "your-password")
headers = {"Authorization": f"Bearer {access_token}"}
Register an Account
def register(email, password, full_name):
"""Create a new account."""
res = requests.post(f"{BASE_URL}/api/v1/auth/register", json={
"email": email,
"password": password,
"full_name": full_name,
})
res.raise_for_status()
data = res.json()
return data["user"], data["tokens"]
user, tokens = register("ada@example.com", "securepass123", "Ada Lovelace")
print(f"Welcome, {user['full_name']}!")
Upload a Document
def upload_document(org_id, file_path):
"""Upload a document for processing."""
with open(file_path, "rb") as f:
res = requests.post(
f"{BASE_URL}/api/v1/documents/upload",
params={"org_id": org_id},
headers=headers,
files={"file": f},
)
res.raise_for_status()
return res.json()
doc = upload_document("your-org-id", "syllabus.pdf")
print(f"Uploaded: {doc['id']} ({doc['doc_type']})")
List Documents
def list_documents(org_id):
"""List all documents in an organization."""
res = requests.get(
f"{BASE_URL}/api/v1/documents/",
params={"org_id": org_id},
headers=headers,
)
res.raise_for_status()
return res.json()
data = list_documents("your-org-id")
for doc in data["items"]:
tags = ", ".join(t["name"] for t in doc.get("tags", []))
print(f" {doc['filename']} ({doc['doc_type']}) - {doc.get('uploaded_by_name', 'Unknown')}")
if tags:
print(f" Tags: {tags}")
Run Compliance Check
def run_compliance(document_id, tiers=None):
"""Run a compliance check on a document."""
body = {"document_id": document_id}
if tiers:
body["tiers"] = tiers
res = requests.post(
f"{BASE_URL}/api/v1/compliance/test",
headers={**headers, "Content-Type": "application/json"},
json=body,
)
res.raise_for_status()
return res.json()
report = run_compliance(doc["id"])
print(f"Score: {report['overall_score']}% (Grade {report['grade']})")
print(f"Passed: {report['total_passed']}/{report['total_checks']}")
# Show failed checks
for check in report.get("checks", []):
if not check["passed"]:
print(f" [{check['severity']}] {check['details']}")
Start a Conversion
import time
def convert_document(document_id):
"""Start a conversion job and poll until complete."""
# Start the job
res = requests.post(
f"{BASE_URL}/api/v1/conversions/",
headers={**headers, "Content-Type": "application/json"},
json={"document_id": document_id},
)
res.raise_for_status()
job = res.json()
job_id = job["job_id"]
print(f"Job started: {job_id}")
# Poll for completion
while True:
res = requests.get(
f"{BASE_URL}/api/v1/conversions/{job_id}",
headers=headers,
)
res.raise_for_status()
status = res.json()
print(f" Status: {status['status']}")
for step in status.get("steps", []):
duration = f" ({step['duration_ms']}ms)" if step.get("duration_ms") else ""
print(f" {step['step_name']}: {step['status']}{duration}")
if status["status"] in ("completed", "failed", "error"):
return status
time.sleep(2)
result = convert_document(doc["id"])
Manage Tags
def create_tag(org_id, name, color=None):
"""Create a tag for an organization."""
body = {"name": name, "org_id": org_id}
if color:
body["color"] = color
res = requests.post(
f"{BASE_URL}/api/v1/tags",
headers={**headers, "Content-Type": "application/json"},
json=body,
)
res.raise_for_status()
return res.json()
def tag_document(tag_id, document_id):
"""Add a tag to a document."""
res = requests.post(
f"{BASE_URL}/api/v1/tags/{tag_id}/documents/{document_id}",
headers=headers,
)
res.raise_for_status()
tag = create_tag("your-org-id", "reviewed", "green")
tag_document(tag["id"], doc["id"])
Share a Document
def share_with_user(document_id, email, permission="view"):
"""Share a document with a user by email."""
res = requests.post(
f"{BASE_URL}/api/v1/documents/{document_id}/shares",
headers={**headers, "Content-Type": "application/json"},
json={"user_email": email, "permission": permission},
)
res.raise_for_status()
return res.json()
def create_public_link(document_id):
"""Create a public read-only link."""
res = requests.post(
f"{BASE_URL}/api/v1/documents/{document_id}/public-share",
headers={**headers, "Content-Type": "application/json"},
json={},
)
res.raise_for_status()
return res.json()
share = share_with_user(doc["id"], "colleague@example.com")
public = create_public_link(doc["id"])
print(f"Public link: {public['url']}")
Batch Upload and Score
from pathlib import Path
def batch_upload_and_score(org_id, directory):
"""Upload all documents in a directory and run compliance checks."""
results = []
supported = {".pdf", ".docx", ".pptx", ".html"}
for file_path in Path(directory).iterdir():
if file_path.suffix.lower() not in supported:
continue
print(f"Uploading {file_path.name}...")
try:
doc = upload_document(org_id, str(file_path))
report = run_compliance(doc["id"])
results.append({
"file": file_path.name,
"score": report["overall_score"],
"grade": report["grade"],
"doc_id": doc["id"],
})
print(f" Score: {report['overall_score']}% ({report['grade']})")
except requests.HTTPError as e:
results.append({"file": file_path.name, "error": str(e)})
print(f" Error: {e}")
return results
results = batch_upload_and_score("your-org-id", "./course-materials")
Token Refresh
def refresh_token_flow(current_refresh_token):
"""Get a new access token using the refresh token."""
res = requests.post(
f"{BASE_URL}/api/v1/auth/refresh",
json={"refresh_token": current_refresh_token},
)
res.raise_for_status()
data = res.json()
return data["access_token"], data["refresh_token"]
# When access token expires (15 min), refresh it
new_access, new_refresh = refresh_token_flow(refresh_token)
headers["Authorization"] = f"Bearer {new_access}"
Error Handling
def safe_request(method, path, **kwargs):
"""Make an API request with proper error handling."""
try:
res = requests.request(method, f"{BASE_URL}{path}", headers=headers, **kwargs)
res.raise_for_status()
if res.status_code == 204:
return None
return res.json()
except requests.HTTPError as e:
status = e.response.status_code
if status == 401:
print("Token expired. Call refresh_token_flow().")
elif status == 403:
print("Permission denied. Check your org membership.")
elif status == 404:
print("Resource not found.")
elif status == 429:
print("Rate limited. Wait and retry.")
else:
detail = e.response.json().get("detail", e.response.text)
print(f"API error {status}: {detail}")
return None
except requests.ConnectionError:
print("Could not connect to API.")
return None