AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Developers Use the ChatPDF API for Automated Document Ingestion, Streaming Chat, and Page-Level Citations

Ana Lázaro Touza · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Software developers use the ChatPDF REST API (https://api.chatpdf.com/v1) to bypass the engineering friction of building and maintaining custom Retrieval-Augmented Generation (RAG) pipelines. Instead of orchestrating document parsing, text chunking, embedding generation, vector databases, and re-ranking algorithms from scratch, developers pass document binaries or URLs to ChatPDF, receive a persistent source identifier, and immediately run conversational queries. By combining stream: true with referenceSources: true, applications deliver real-time token streaming alongside verifiable page citations ([P<N>]), anchoring generated answers directly to source pages.

At 365Finds, our commercial verdict is decisive: for software teams with fewer than two dedicated machine learning engineers needing document-grounded intelligence inside production apps, ChatPDF API is an exceptional operational shortcut. It reduces months of vector infrastructure maintenance to three standard HTTP requests. However, adopting it requires engineering around its stateless design, a hard 6-message/2,500-token context limit per call, and file-size constraints (2,000 pages or 32 MB per PDF).


Architectural Comparison: Headless RAG vs. In-House RAG Pipeline

Before writing code, backend architects must weigh whether an external headless document API fits their technical and commercial profile. Building custom RAG affords granular model choice and private VPC deployments, but demands substantial DevOps overhead.

Architectural DimensionChatPDF Headless REST APIIn-House RAG Pipeline (LangChain, LlamaIndex, pgvector)
Initial Implementation TimeUnder 1 day (standard REST calls)3 to 6 weeks (chunking, vector DB setup, tuning)
Infrastructure FootprintZero vector DB servers, zero embedding computeVector DB cluster (Pinecone, Qdrant, Milvus), embedding worker nodes
PDF Extraction & OCRManaged server-side parsing (up to 2,000 pages)Self-hosted OCR engines (Tesseract, PyMuPDF, Unstructured)
Citation PrecisionBuilt-in page citation tags ([P<N>]) and structured arraysCustom metadata tracking across chunk boundaries and re-rankers
Real-Time StreamingNative HTTP streaming / chunked responseRequires custom SSE / WebSocket pipe from LLM client to frontend
Session State ManagementStateless (caller manages conversation history)Managed in application memory or conversational state store
Ingestion CeilingMax 32 MB or 2,000 pages per PDFConfigurable, constrained only by infrastructure budget
Data Lifecycle ControlAutomated remote purge via POST /sources/deleteFull database row deletion and vector indexing control

365Finds views ChatPDF API as an ideal solution for SaaS document assistants, legal document viewers, customer knowledge portals, and compliance search bots where quick time-to-market and rock-solid citation trust take precedence over deep custom embedding fine-tuning.


1. Authentication and Base Setup

The ChatPDF API uses an API key issued from the ChatPDF developer portal. Every outbound HTTP request must supply this key inside the x-api-key header.

Developers should store this key in environment variables (CHATPDF_API_KEY) and avoid exposing it on browser clients. All calls should pass through your secure backend proxy or serverless function.


2. Ingesting Documents: File Upload vs. Public URL

ChatPDF supports two automated ingestion paths to transform unstructured PDFs into indexed vector knowledge bases, returning a unique sourceId.

Method A: Local Binary Upload (/sources/add-file)

Use this endpoint when processing user-uploaded files, local disk assets, or private document stores that cannot be exposed via public URLs.

Python Implementation:

import os
import requests

API_KEY = os.getenv("CHATPDF_API_KEY")
UPLOAD_ENDPOINT = "https://api.chatpdf.com/v1/sources/add-file"

def upload_local_pdf(file_path: str) -> str:
    """Uploads a local PDF file and returns the generated sourceId."""
    headers = {
        "x-api-key": API_KEY
    }
    
    with open(file_path, "rb") as pdf_file:
        files = {
            "file": (os.path.basename(file_path), pdf_file, "application/pdf")
        }
        response = requests.post(UPLOAD_ENDPOINT, headers=headers, files=files, timeout=60)
        
    if response.status_code == 200:
        data = response.json()
        return data["sourceId"]  # e.g., "src_abc123xyz"
    else:
        raise RuntimeError(f"ChatPDF upload failed [{response.status_code}]: {response.text}")

Method B: Public URL Ingestion (/sources/add-url)

If your documents reside in Amazon S3, Google Cloud Storage, or public web repositories with pre-signed or public URLs, passing the URL allows ChatPDF's backend to fetch and ingest the file directly without intermediate transit through your server memory.

Node.js / TypeScript Implementation:

interface AddUrlResponse {
  sourceId: string;
}

export async function ingestPdfFromUrl(documentUrl: string): Promise<string> {
  const apiKey = process.env.CHATPDF_API_KEY;
  if (!apiKey) throw new Error("Missing CHATPDF_API_KEY environment variable");

  const response = await fetch("https://api.chatpdf.com/v1/sources/add-url", {
    method: "POST",
    headers: {
      "x-api-key": apiKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ url: documentUrl }),
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Ingestion failed with status ${response.status}: ${errorText}`);
  }

  const result = (await response.json()) as AddUrlResponse;
  return result.sourceId; // e.g., "src_def456uvw"
}

Operational Note: For documents uploaded manually through the ChatPDF web interface (chatpdf.com/c/{chatId}), the corresponding API source ID uses the prefix cha_ followed by the chat slug (for example, cha_zNXgrtLfhbFw7KabJgE1). Programmatically uploaded sources carry the src_ prefix.


3. Stateless Conversation Design and Context Buffer Rules

The ChatPDF chat endpoint (POST /v1/chats/message) is completely stateless. The backend retains the document vectors under sourceId, but does not store conversation threads across calls. Your application database (PostgreSQL, MongoDB, or Redis) must manage user conversation history.

Constraints Imposed by ChatPDF:

  1. Message Count Limit: You can supply up to 6 messages in the messages array per request.
  2. Context Token Ceiling: If the cumulative OpenAI token count of the submitted messages exceeds 2,500 tokens, the API silently drops older messages until the payload fits within 2,500 tokens.
  3. Role Structure: Only "user" and "assistant" roles are permitted.

To avoid erratic conversational amnesia caused by automatic message pruning, developers must enforce a rolling window on their application server before dispatching requests.

Rolling Context Buffer Example (Python):

def prepare_chat_payload(source_id: str, history: list[dict], new_question: str) -> dict:
    """
    Assembles a balanced conversation payload respecting the 6-message rule.
    History contains [{"role": "user"|"assistant", "content": "..."}].
    """
    # Keep up to the last 5 turns to leave slot 6 for the incoming question
    trimmed_history = history[-5:] if len(history) > 5 else list(history)
    
    messages = trimmed_history + [{"role": "user", "content": new_question}]
    
    return {
        "sourceId": source_id,
        "messages": messages,
        "referenceSources": True,
        "stream": True
    }

4. Streaming Responses with Server-Sent Events (SSE)

By default, /v1/chats/message blocks until the complete answer is generated, which can take 3 to 8 seconds for dense academic or corporate documents. Setting "stream": true returns an HTTP chunked stream that transmits tokens word-by-word.

Real-Time Streaming Client in Node.js

import { Readable } from "node:stream";

export async function streamDocumentChat(
  sourceId: string,
  messages: Array<{ role: "user" | "assistant"; content: string }>,
  onToken: (token: string) => void
): Promise<string> {
  const apiKey = process.env.CHATPDF_API_KEY!;
  
  const response = await fetch("https://api.chatpdf.com/v1/chats/message", {
    method: "POST",
    headers: {
      "x-api-key": apiKey,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      sourceId,
      messages,
      referenceSources: true,
      stream: true,
    }),
  });

  if (!response.ok || !response.body) {
    throw new Error(`Chat request failed: ${response.status} ${response.statusText}`);
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder("utf-8");
  let accumulatedAnswer = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    const chunk = decoder.decode(value, { stream: true });
    accumulatedAnswer += chunk;
    onToken(chunk); // Emit immediately to UI via WebSocket or Next.js route stream
  }

  return accumulatedAnswer;
}

Real-Time Streaming Client in Python

def stream_chatpdf_query(source_id: str, query: str):
    """Streams token chunks to stdout as they arrive from ChatPDF."""
    endpoint = "https://api.chatpdf.com/v1/chats/message"
    headers = {
        "x-api-key": os.getenv("CHATPDF_API_KEY"),
        "Content-Type": "application/json"
    }
    payload = {
        "sourceId": source_id,
        "referenceSources": True,
        "stream": True,
        "messages": [{"role": "user", "content": query}]
    }

    with requests.post(endpoint, headers=headers, json=payload, stream=True, timeout=30) as r:
        r.raise_for_status()
        full_text = ""
        for chunk in r.iter_content(chunk_size=None, decode_unicode=True):
            if chunk:
                print(chunk, end="", flush=True)
                full_text += chunk
        return full_text

5. Page-Level Citation Extraction and PDF Viewer Synchronization

Trust is the single most important factor when users query financial audits, medical research, or legal contracts. Including "referenceSources": true in your request forces ChatPDF to provide exact page-level provenance.

Non-Streaming vs. Streaming Citation Behavior

Parsing Citations and Linking to PDF Viewers

To create an interactive reading experience where clicking a citation automatically scrolls an embedded PDF viewer (such as PDF.js or React-PDF) to the target page, parse the incoming tokens using a regular expression:

export interface ExtractedCitation {
  rawTag: string;
  pageNumber: number;
}

export function extractCitations(responseText: string): {
  sanitizedText: string;
  citations: ExtractedCitation[];
} {
  const citationRegex = /\[P(\d+)\]/g;
  const citations: ExtractedCitation[] = [];
  let match: RegExpExecArray | null;

  while ((match = citationRegex.exec(responseText)) !== null) {
    citations.push({
      rawTag: match[0],
      pageNumber: parseInt(match[1], 10),
    });
  }

  // Deduplicate page numbers
  const uniqueCitations = citations.filter(
    (item, index, self) => index === self.findIndex((c) => c.pageNumber === item.pageNumber)
  );

  return {
    sanitizedText: responseText,
    citations: uniqueCitations,
  };
}

In your frontend UI, replace [P12] tokens with clickable chip components:

// Frontend button triggering PDF viewer scroll
<button onClick={() => pdfViewerRef.current.goToPage(citation.pageNumber)}>
  Page {citation.pageNumber}
</button>

6. Document Lifecycle Cleanup and Compliance

Enterprise applications handling confidential documents or governed by GDPR/CCPA cannot leave PDF embeddings stored indefinitely in third-party databases. When a user deletes a file or completes an analytical session, your application must issue a deletion call.

def purge_documents(source_ids: list[str]) -> bool:
    """Purges one or more ingested sources from ChatPDF storage."""
    delete_endpoint = "https://api.chatpdf.com/v1/sources/delete"
    headers = {
        "x-api-key": os.getenv("CHATPDF_API_KEY"),
        "Content-Type": "application/json"
    }
    resp = requests.post(delete_endpoint, headers=headers, json={"sources": source_ids}, timeout=15)
    return resp.status_code == 200

365Finds strongly advises implementing automated deletion hooks. Whenever a workspace or chat session is archived in your database, execute a cleanup worker to purge the associated sourceId references immediately.


365Finds Strategic Assessment: When to Adopt and When to Walk Away

ChatPDF API offers high utility, but software engineers must recognize its exact boundary conditions:

Adopt ChatPDF API If:

Build Custom In-House RAG If:

For 80% of standard enterprise document Q&A use cases, starting with ChatPDF API accelerates delivery by months while maintaining dependable precision and citation transparency.


References