aily API into any Python application using the requests library or httpx. Includes sync and async examples.">

Using classifaily with Python

Integrate the classifaily API into any Python application using the requests library or httpx. Includes sync and async examples.

Prerequisites

pip install requests

Store your API key in an environment variable - never hardcode it in source files:

export CLASSIFAILY_KEY="cai_live_your_key_here"

Basic classify request

import os
import requests

API_KEY = os.environ["CLASSIFAILY_KEY"]
BASE_URL = "https://api.classifaily.com/v1"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}

response = requests.post(
    f"{BASE_URL}/classify",
    headers=headers,
    json={
        "input": "My invoice shows a double charge this month.",
        "categories": ["billing", "technical_bug", "account_access", "general"],
    },
    timeout=10,
)
response.raise_for_status()

data = response.json()
print(data["result"]["label"])       # billing
print(data["result"]["confidence"])  # 0.97

Reusable client class

import os
import requests

class ClassifailyClient:
    BASE_URL = "https://api.classifaily.com/v1"

    def __init__(self, api_key: str | None = None):
        self.session = requests.Session()
        self.session.headers.update({
            "Authorization": f"Bearer {api_key or os.environ['CLASSIFAILY_KEY']}",
            "Content-Type": "application/json",
        })

    def classify(self, input: str, categories: list[str], explain: bool = False) -> dict:
        payload = {"input": input, "categories": categories}
        if explain:
            payload["explain"] = True
        resp = self.session.post(f"{self.BASE_URL}/classify", json=payload, timeout=10)
        resp.raise_for_status()
        return resp.json()["result"]

    def batch(self, items: list[dict], categories: list[str]) -> list[dict]:
        resp = self.session.post(
            f"{self.BASE_URL}/batch",
            json={"items": items, "categories": categories},
            timeout=30,
        )
        resp.raise_for_status()
        return resp.json()["results"]


# Usage
client = ClassifailyClient()
result = client.classify(
    "Cannot log in after password reset.",
    ["billing", "technical_bug", "account_access", "general"],
)

if result["confidence"] > 0.80:
    route_ticket(result["label"])
else:
    flag_for_review()

Batch classification

items = [
    {"id": "q1", "input": "Cannot log in after password reset."},
    {"id": "q2", "input": "Refund request for last month."},
    {"id": "q3", "input": "Please add dark mode."},
]

results = client.batch(items, ["billing", "technical_bug", "account_access", "feature_request"])

for r in results:
    print(f"{r['id']}: {r['result']['label']} ({r['result']['confidence']:.2f})")

Async with httpx

pip install httpx
import os
import httpx
import asyncio

async def classify_async(text: str, categories: list[str]) -> dict:
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            "https://api.classifaily.com/v1/classify",
            headers={"Authorization": f"Bearer {os.environ['CLASSIFAILY_KEY']}"},
            json={"input": text, "categories": categories},
            timeout=10,
        )
        resp.raise_for_status()
        return resp.json()["result"]

result = asyncio.run(classify_async(
    "My subscription was charged twice.",
    ["billing", "technical_bug", "account_access", "general"],
))
Ready to integrate?

See the full API reference for all parameters and response schemas.

API Reference