For engineering teams building generative search, legal review portals, or automated compliance pipelines, embedding a third-party chat widget via an iframe is a non-starter. Production backend services demand deterministic document lifecycle hooks, granular tenant folder isolation, tight role-based access control (RBAC), and direct access to structured citation metadata.
Humata provides a dedicated REST API designed to bypass the consumer web interface entirely. Through its programmatic endpoints, backend developers can ingest PDFs directly from cloud object storage (such as AWS S3 or Google Cloud Storage signed URLs), track document parsing states, create dedicated multi-document conversation sessions, and stream cited responses via Server-Sent Events (SSE).
At 365Finds, our assessment is straightforward: Humata is one of the most reliable managed document-intelligence engines for long-form PDF interrogation, but only if you design your backend around its asynchronous processing constraints and enforce strict grounding parameters. This guide provides an end-to-end technical blueprint for software engineers implementing the Humata REST API within modern microservices.
1. Authentication and Architecture Overview
Humata exposes its REST API via the base endpoint https://app.humata.ai/api. Authentication relies on standard HTTP Bearer tokens passed via the Authorization header.
Generating API Credentials
To generate an API key:
- Log into your organization account at Humata.
- Navigate to Developer Settings (
https://app.humata.ai/settings/developers). This action requires Organization Admin privileges. - Click Generate API Key and store the secret in your secret management system (e.g., AWS Secrets Manager, HashiCorp Vault, or encrypted environment variables).
# Authorization Header Syntax
Authorization: Bearer YOUR_HUMATA_API_KEY
End-to-End Ingestion and Query Pipeline
[Cloud Storage (S3/GCS)]
│ (Signed URL)
▼
[Backend Microservice] ──(POST /v2/import-url)──► [Humata Ingestion Engine]
│ │ (Async OCR & Indexing)
│◄──(Poll GET /v1/pdf/{id} until SUCCESS)────────────┘
▼
[Create Conversation Session] ──(POST /v1/conversations)──► [Conversation State]
▼
[Client Query Execution] ──(POST /v1/ask)──────────────► [Humata LLM & Vector Store]
│ │
│◄──(text/event-stream SSE Response)─────────────────┘
▼
[SSE Token Buffer & Citation Parser]
│
▼
[Frontend: Streamed Markdown + Clickable Page Citation Badges]
Key API Endpoints at a Glance
| Action | Endpoint | Method | Key Parameters |
|---|---|---|---|
| Import PDF via URL | /api/v2/import-url | POST | url, folder_id |
| Check Document Status | /api/v1/pdf/{pdf-id} | GET | Path parameter pdf-id |
| Initialize Conversation | /api/v1/conversations | POST | documentIds (array of UUIDs) |
| Stream Cited Q&A | /api/v1/ask | POST | conversationId, question, model, selectedAnswerApproach |
| Provision User Accounts | /api/v1/users | POST | first_name, last_name, email, password |
2. Step 1: Asynchronous Document Ingestion via /api/v2/import-url
Direct file uploads via multipart form data can exhaust memory and saturate HTTP connections on backend gateway proxies when dealing with 500-page regulatory filings or multi-gigabyte document batches. Humata circumvents this by fetching documents directly from an external URL.
Endpoint Specification
- Route:
POST https://app.humata.ai/api/v2/import-url - Headers:
Authorization: Bearer <API_KEY>Content-Type: application/json
- Request Payload:
url(string, URI, required): A publicly reachable or time-limited pre-signed URL pointing directly to the PDF binary.folder_id(string, UUID, required): The UUID of the workspace folder where the document must reside.
Request Example
{
"url": "https://storage.enterprise.internal/compliance/2026-audit-report.pdf?X-Amz-Signature=...",
"folder_id": "e507832b-bdef-4baf-8423-822c1cb68e35"
}
Response Example (200 OK)
{
"id": "a8283bc7-02ee-471b-8590-5ef5401afa40"
}
365Finds Architecture Recommendation: Always set an expiration window of at least 15 to 30 minutes on AWS S3 or GCS signed URLs. Large PDFs require time for Humata's background workers to queue, download, and initiate parsing. If your pre-signed URL expires in 60 seconds, Humata's asynchronous worker will fail to fetch the document.
3. Step 2: Ingestion Polling and Lifecycle Verification
The POST /api/v2/import-url call returns almost immediately once the job is acknowledged. However, the document is not ready for querying. Humata must extract text, run optical character recognition (OCR) on scanned diagrams, generate vector embeddings, and construct semantic indexes.
Querying a document while it is still processing will trigger an error or return empty retrieval contexts. Backend applications must poll the PDF status endpoint until parsing completes.
Endpoint Specification
- Route:
GET https://app.humata.ai/api/v1/pdf/{pdf-id} - Headers:
Authorization: Bearer <API_KEY>
Processing Status Schema
{
"id": "a8283bc7-02ee-471b-8590-5ef5401afa40",
"name": "2026-audit-report.pdf",
"organization_id": "fcf6c954-ba68-4e39-a7b5-960dc8274ec0",
"created_at": "2026-11-01T20:18:53.289618+00:00",
"updated_at": "2026-11-01T20:19:15.584786+00:00",
"number_of_pages": 84,
"folder_id": "e507832b-bdef-4baf-8423-822c1cb68e35",
"read_status": "SUCCESS",
"created_by": "07f5bfc7-72c9-40b7-8151-dcfc2f9613dc",
"from_url": "https://storage.enterprise.internal/compliance/2026-audit-report.pdf",
"file_type": "PDF"
}
Polling State Machine Logic
Your backend worker should monitor read_status:
SUCCESS: Ingestion finished; proceed to conversation creation.FAILED: Parsing failed (e.g., corrupted PDF structure, DRM/password protection, or download timeout). Log an alert and abort.PENDING/ Other: Continue polling with exponential backoff (e.g., initial interval 2 seconds, multiplier 1.5, max backoff 15 seconds, timeout at 180 seconds).
4. Step 3: Initializing Conversation Context via /api/v1/conversations
Humata decouples documents from query sessions. To ask questions against one or more indexed PDFs, you must first create a conversation bound to those specific document IDs.
Endpoint Specification
- Route:
POST https://app.humata.ai/api/v1/conversations - Headers:
Authorization: Bearer <API_KEY>Content-Type: application/json
- Request Payload:
documentIds(array of UUID strings, required): The list of document IDs to attach to the conversation session.
Request Example
{
"documentIds": [
"a8283bc7-02ee-471b-8590-5ef5401afa40",
"cbec39d9-1e01-409c-9fc2-f19f5d01005c"
]
}
Response Example (200 OK)
{
"id": "7290fd6b-fe15-4fd3-865e-8010bd8e8a38"
}
The returned id is your conversationId. Persist this identifier in your application database alongside your internal user or session records to support continuous multi-turn conversations.
5. Step 4: Streaming Cited Q&A via Server-Sent Events (SSE)
The core value of Humata lies in its ability to stream generated answers while supplying exact page-level citations for every factual claim.
Endpoint Specification
- Route:
POST https://app.humata.ai/api/v1/ask - Headers:
Authorization: Bearer <API_KEY>Content-Type: application/jsonAccept: text/event-stream
- Request Payload Parameters:
conversationId(string, UUID, required): The active conversation identifier.question(string, required): The user's natural language question.model(string, required): Supported model identifiers (e.g.,gpt-4o,gpt-4-turbo-preview,gpt-4.1-mini).selectedAnswerApproach(string, optional): Grounding mode:Grounded: Restricts answers strictly to verifiable facts extracted from the attached documents.Balanced: Allows standard contextual synthesis with moderate reasoning latitude.Creative: Looser creative generation (not recommended for compliance or enterprise tasks).
365Finds Institutional Judgment: In production microservices, never omit
selectedAnswerApproachand never default toCreative. We strongly recommend enforcing"selectedAnswerApproach": "Grounded"for all business workflows. In regulated domains (legal, finance, and engineering specs), an ungrounded hallucination that cannot be tied to a document page invalidates the entire purpose of deploying Humata over a standard ungrounded LLM.
Request Payload Example
{
"conversationId": "7290fd6b-fe15-4fd3-865e-8010bd8e8a38",
"model": "gpt-4o",
"question": "What is the liability cap under Section 12, and what are the carve-outs?",
"selectedAnswerApproach": "Grounded"
}
Understanding the Raw SSE Response Stream
Humata emits chunks conforming to the Server-Sent Events standard (text/event-stream). Each line starts with data: :
data: { 'content': 'Under Section 12.1, the aggregate liability cap is limited to ' }
data: { 'content': 'fees paid in the prior twelve months[1]. ' }
data: { 'content': 'However, gross negligence, confidentiality breaches, and IP indemnification ' }
data: { 'content': 'are explicitly carved out from this limitation[2].' }
data: { 'content': '\n\nReferences - [1]: Page 28 of 2026-audit-report.pdf\nReferences - [2]: Page 29 of 2026-audit-report.pdf' }
Anatomy of Humata Citations
Humata uses a two-part citation mechanism:
- Inline Marker:
[N]inserted directly into the streamed prose. - Citation Trailer: At the conclusion of the stream, Humata appends reference lines formatted as:
References - [N]: Page <PAGE_NUM> of <FILENAME>
To deliver a polished user experience, your backend or frontend parser must buffer the stream, stream the tokens to the UI, and parse the trailer lines into interactive citation links that jump directly to <PAGE_NUM> in your embedded document viewer.
6. Full Production Implementation: Python & FastAPI
Below is a complete, production-ready Python service using httpx and FastAPI that implements the full lifecycle: URL-based import, exponential-backoff polling, conversation binding, and SSE proxy streaming with citation extraction.
import asyncio
import json
import re
from typing import AsyncGenerator, Dict, Any, List
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, HttpUrl
app = FastAPI(title="Humata Enterprise Ingestion Bridge")
HUMATA_BASE_URL = "https://app.humata.ai/api"
HUMATA_API_KEY = "YOUR_HUMATA_API_KEY"
HEADERS = {
"Authorization": f"Bearer {HUMATA_API_KEY}",
"Content-Type": "application/json",
}
class IngestRequest(BaseModel):
pdf_url: HttpUrl
folder_id: str
class AskRequest(BaseModel):
conversation_id: str
question: str
model: str = "gpt-4o"
grounding: str = "Grounded"
# 1. Asynchronous Document Ingestion
async def import_document_url(client: httpx.AsyncClient, pdf_url: str, folder_id: str) -> str:
payload = {"url": str(pdf_url), "folder_id": folder_id}
response = await client.post(f"{HUMATA_BASE_URL}/v2/import-url", json=payload, headers=HEADERS)
if response.status_code != 200:
raise HTTPException(status_code=response.status_code, detail=f"Import failed: {response.text}")
data = response.json()
return data["id"]
# 2. Polling Ingestion Status with Exponential Backoff
async def wait_for_document_indexing(
client: httpx.AsyncClient,
pdf_id: str,
timeout_sec: int = 180
) -> Dict[str, Any]:
elapsed = 0
interval = 2.0
while elapsed < timeout_sec:
response = await client.get(f"{HUMATA_BASE_URL}/v1/pdf/{pdf_id}", headers=HEADERS)
if response.status_code != 200:
raise HTTPException(status_code=response.status_code, detail=f"Status check failed: {response.text}")
pdf_meta = response.json()
status = pdf_meta.get("read_status")
if status == "SUCCESS":
return pdf_meta
if status == "FAILED":
raise HTTPException(status_code=500, detail="Humata PDF parsing failed.")
await asyncio.sleep(interval)
elapsed += interval
interval = min(interval * 1.5, 10.0) # Smooth exponential backoff
raise HTTPException(status_code=504, detail="Document ingestion timed out.")
# 3. Conversation Initialization
async def create_conversation_session(client: httpx.AsyncClient, document_ids: List[str]) -> str:
payload = {"documentIds": document_ids}
response = await client.post(f"{HUMATA_BASE_URL}/v1/conversations", json=payload, headers=HEADERS)
if response.status_code != 200:
raise HTTPException(status_code=response.status_code, detail=f"Failed to create conversation: {response.text}")
return response.json()["id"]
# Pipeline Endpoint: Ingest & Bind Session
@app.post("/api/v1/documents/ingest-and-bind")
async def ingest_pipeline(req: IngestRequest):
async with httpx.AsyncClient(timeout=30.0) as client:
# Step 1: Queue import
pdf_id = await import_document_url(client, str(req.pdf_url), req.folder_id)
# Step 2: Poll until ready
pdf_meta = await wait_for_document_indexing(client, pdf_id)
# Step 3: Initialize multi-turn conversation
conv_id = await create_conversation_session(client, [pdf_id])
return {
"status": "ready",
"pdf_id": pdf_id,
"conversation_id": conv_id,
"pages": pdf_meta.get("number_of_pages"),
"filename": pdf_meta.get("name")
}
# 4. SSE Stream Proxy with Citation Extraction
async def stream_humata_ask(
conversation_id: str,
question: str,
model: str,
approach: str
) -> AsyncGenerator[str, None]:
payload = {
"conversationId": conversation_id,
"model": model,
"question": question,
"selectedAnswerApproach": approach,
}
citation_regex = re.compile(r"References\s*-\s*\[(\d+)\]:\s*Page\s*(\d+)\s*of\s*(.+)")
async with httpx.AsyncClient(timeout=120.0) as client:
async with client.stream(
"POST",
f"{HUMATA_BASE_URL}/v1/ask",
json=payload,
headers={**HEADERS, "Accept": "text/event-stream"}
) as response:
if response.status_code != 200:
err_body = await response.aread()
yield f"data: {json.dumps({'error': f'Humata ask error: {err_body.decode()}'})}\n\n"
return
async for line in response.aiter_lines():
if not line or not line.startswith("data:"):
continue
raw_chunk = line[5:].strip()
# Parse json chunk: {'content': '...'}
try:
# Replace single quotes if Humata returns single-quoted JSON string
formatted = raw_chunk.replace("'", '"')
data_obj = json.loads(formatted)
content = data_obj.get("content", "")
except Exception:
content = raw_chunk
# Detect if the chunk contains reference trailer information
ref_match = citation_regex.search(content)
if ref_match:
ref_idx, page_num, doc_name = ref_match.groups()
payload_out = {
"type": "citation",
"ref_id": int(ref_idx),
"page": int(page_num),
"document": doc_name.strip()
}
else:
payload_out = {
"type": "token",
"text": content
}
yield f"data: {json.dumps(payload_out)}\n\n"
@app.post("/api/v1/chat/stream")
async def chat_stream(req: AskRequest):
return StreamingResponse(
stream_humata_ask(req.conversation_id, req.question, req.model, req.grounding),
media_type="text/event-stream"
)
7. Rate Limits, Error Handling, and Operational Guardrails
Integrating the Humata API in mission-critical applications requires handling specific operational boundaries:
Rate Limiting (120 req/min)
Humata enforces a default threshold of 120 requests per minute. Responses exceeding this limit return HTTP 429 Too Many Requests with the following rate-limit response headers:
X-RateLimit-Limit: Maximum requests permitted per window.X-RateLimit-Remaining: Remaining request allowance in current window.X-RateLimit-Reset: UTC epoch timestamp indicating when the window resets.
Mitigation Strategy: Implement a token-bucket or sliding-window rate limiter inside your API gateway (such as Kong, Traefik, or Redis-based rate limiters). For enterprise production spikes, email support@humata.ai to negotiate elevated concurrency tiers.
Handling Parsing and Network Errors
- HTTP 401 Unauthorized: Occurs when the API key is missing or revoked. Ensure your deployment checks credential validity upon cold boot.
- HTTP 404 Document Not Found: Occurs if you call
GET /v1/pdf/{pdf-id}with an invalid UUID or if the document belonged to a different organization tenant. - Corrupted or Scanned PDFs: If
read_statusevaluates toFAILED, evaluate whether the source PDF contains password DRM or corrupted font descriptors. Ensure your document preprocessing pipeline cleans and unprotects files before generating pre-signed URLs.
8. 365Finds Strategic Takeaway
Building document intelligence into bespoke enterprise applications does not require training in-house vector databases or maintaining brittle OCR pipelines. Humata’s REST API provides a dependable, turnkey foundation for extracting cited answers from complex PDFs.
However, engineers must respect two foundational architecture rules:
- Never attempt real-time synchronous ingestion within user request loops. PDF OCR and vectorization take time; always decouple ingestion via background worker queues and asynchronous polling.
- Enforce
selectedAnswerApproach: "Grounded"at the API gateway layer. Allowing unconstrained generative approaches erodes user trust and compromises the primary engineering value of Humata: absolute page-level traceability.