AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Developers Automate PDF Ingestion, Querying, and Citation Streaming with the ChatPDF REST API

Zhou Jiajia · 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

Building a custom Retrieval-Augmented Generation (RAG) pipeline for document question-answering is one of the most common engineering traps in modern AI development. Extracting text from complex multi-column layouts, tuning chunking strategies, generating vector embeddings, maintaining vector databases like Pinecone or pgvector, orchestrating hybrid search, and mapping chunks back to precise PDF page numbers can consume weeks of engineering bandwidth. For production workloads where users need fast, accurate answers directly grounded in specific documents, maintaining this infrastructure creates continuous operational overhead and high cloud bills.

At 365Finds, our commercial verdict is straightforward: for 80% of document-grounded applications—including customer support portals, contract analysis tools, compliance auditing, and internal knowledge hubs—building a bespoke vector pipeline is unnecessary. ChatPDF provides a production-ready, fully managed RAG engine accessible through a lean REST API at api.chatpdf.com. With three primary endpoints, developers can upload documents, query them across multi-turn sessions, stream responses token-by-token, and parse exact page citations out of the box.

This guide provides a comprehensive technical walkthrough for software engineers, backend developers, and automation architects looking to integrate ChatPDF into their production systems.


Architectural Comparison: Custom RAG Pipeline vs. ChatPDF REST API

Before committing engineering resources to infrastructure, consider how the operational footprint compares:

Capability / MetricCustom In-House RAG StackChatPDF REST API
Ingestion PipelinePDF layout parsing; chunking heuristics; embedding API callsSingle REST upload; background parsing and indexing completed in seconds
Vector Storage & IndexingPinecone, Qdrant, Weaviate, or pgvector setup; index maintenanceFully managed internal indexing; zero database hosting or maintenance
Citations & VerificationManual metadata tracking per chunk; custom page offset mappingAutomatic inline page citations [P<N>] and structured page arrays
Response LatencyNetwork latency across embedding, vector query, and LLM synthesisDirect HTTP chunked streaming for sub-second Time-To-First-Token (TTFT)
Maintenance BurdenHigh: model upgrades, re-indexing, chunk boundary tuningZero infrastructure maintenance; maintained via standard REST calls
Best Suited ForCross-corpus search across millions of disconnected fragmentsPer-document or bounded multi-document interactive workflows

Authentication and Base Configuration

The ChatPDF API communicates over HTTPS using JSON or multipart form data. All requests require an API key supplied in a custom request header.

Obtain your API key from the ChatPDF developer portal. Store this key securely in environment variables (such as CHATPDF_API_KEY). Never expose your ChatPDF secret key in client-side code (browsers or mobile applications); route all requests through your secure application backend.


Step 1: Automated Document Ingestion

ChatPDF supports document ingestion through two mechanisms: direct file upload (/v1/sources/add-file) and public URL retrieval (/v1/sources/add-url). Both endpoints return a unique sourceId (e.g., src_abc123) that represents the indexed document for all subsequent chat queries.

File Ingestion Limits

Option A: Uploading Local Files via Multipart Form Data

To upload a local PDF file, dispatch a POST request to /v1/sources/add-file. The file data must be sent as multipart/form-data under the field name file.

Python Implementation (requests)

import os
import requests

API_KEY = os.environ.get("CHATPDF_API_KEY")
UPLOAD_URL = "https://api.chatpdf.com/v1/sources/add-file"

def upload_pdf_file(file_path: str) -> str:
    headers = {
        "x-api-key": API_KEY
    }
    with open(file_path, "rb") as f:
        files = [("file", (os.path.basename(file_path), f, "application/pdf"))]
        response = requests.post(UPLOAD_URL, headers=headers, files=files)
    
    if response.status_code == 200:
        data = response.json()
        return data["sourceId"]
    else:
        raise RuntimeError(f"ChatPDF upload failed [{response.status_code}]: {response.text}")

# Example usage
# source_id = upload_pdf_file("./contracts/service_agreement.pdf")
# print(f"Uploaded Source ID: {source_id}")

Option B: Ingesting Remote PDFs via URL

If your application stores documents in cloud object storage (such as AWS S3, Cloudflare R2, or Google Cloud Storage), you do not need to download the file to your application server first. Instead, provide a publicly accessible or pre-signed URL to /v1/sources/add-url.

Node.js / TypeScript Implementation (fetch)

interface AddUrlResponse {
  sourceId: string;
}

async function uploadPdfFromUrl(pdfUrl: string, apiKey: string): Promise<string> {
  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: pdfUrl })
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Failed to ingest PDF URL (${response.status}): ${errorText}`);
  }

  const data = (await response.json()) as AddUrlResponse;
  return data.sourceId;
}

Database Persistence Pattern

When building an enterprise system, store the returned sourceId in your relational database or document store alongside your internal entity identifiers:

CREATE TABLE document_sources (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    workspace_id UUID NOT NULL,
    file_name VARCHAR(255) NOT NULL,
    chatpdf_source_id VARCHAR(64) UNIQUE NOT NULL,
    page_count INT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

Step 2: Querying Documents and Managing Conversation History

Once a document is indexed, queries are submitted to POST https://api.chatpdf.com/v1/chats/message.

Stateless Architecture and Token Budgets

The ChatPDF chat endpoint is stateless. The server does not maintain conversational context between successive HTTP calls. To build a multi-turn conversational experience, your application backend must persist previous conversation turns and pass them inside the messages payload.

ChatPDF enforces two conversation bounds:

  1. Message limit: A maximum of 6 messages can be included in a single request.
  2. Context token limit: The cumulative dialogue history in messages must not exceed 2,500 OpenAI tokens. If the token count exceeds 2,500, ChatPDF automatically drops the oldest messages until the payload fits within limits.

Non-Streaming Request Payload Structure

{
  "sourceId": "src_xxxxxx",
  "referenceSources": true,
  "messages": [
    {
      "role": "user",
      "content": "What are the termination conditions specified in Section 8?"
    }
  ]
}

Handling Structured Page References

When "referenceSources": true is set, ChatPDF embeds bracketed citation tags directly into the generated answer text (such as [P12]) and includes a top-level references array listing all referenced pages:

{
  "content": "According to Section 8.2, either party may terminate the agreement upon 30 days written notice [P12]. Immediate termination applies under breach of confidentiality [P15].",
  "references": [
    { "pageNumber": 12 },
    { "pageNumber": 15 }
  ]
}

Step 3: Implementing Word-by-Word Response Streaming

In user-facing AI applications, waiting several seconds for a full document synthesis causes unacceptable interface latency. ChatPDF supports real-time token streaming by setting "stream": true in the request body.

Unlike some APIs that wrap stream chunks in Server-Sent Events (data: {...} lines), ChatPDF streams raw text chunks directly using standard HTTP chunked transfer encoding.

Streaming with Python (requests)

import json
import requests

def stream_chat_response(source_id: str, prompt: str, api_key: str):
    url = "https://api.chatpdf.com/v1/chats/message"
    headers = {
        "x-api-key": api_key,
        "Content-Type": "application/json"
    }
    payload = {
        "sourceId": source_id,
        "stream": True,
        "referenceSources": True,
        "messages": [
            {"role": "user", "content": prompt}
        ]
    }

    response = requests.post(url, headers=headers, json=payload, stream=True)
    if response.status_code != 200:
        raise RuntimeError(f"ChatPDF stream error [{response.status_code}]: {response.text}")

    # Consume raw chunks progressively
    for chunk in response.iter_content(chunk_size=None, decode_unicode=True):
        if chunk:
            yield chunk

Step 4: Parsing Citations from Real-Time Streams

When combining "stream": true and "referenceSources": true, ChatPDF outputs tokens in real time, embedding tags in the format [P<N>] (e.g., [P4], [P102]). Because streaming returns raw text rather than a closing JSON payload with the references array, your backend or frontend stream parser must extract these tags dynamically.

Dynamic Stream Parser Implementation (TypeScript / Web Streams)

Here is a robust stream processor that consumes incoming chunks, yields readable text to the UI, and tracks unique cited page numbers:

import { Readable } from "stream";

interface StreamResult {
  fullText: string;
  citedPages: number[];
}

export async function processChatPdfStream(
  responseStream: ReadableStream<Uint8Array>,
  onToken?: (token: string) => void
): Promise<StreamResult> {
  const reader = responseStream.getReader();
  const decoder = new TextDecoder("utf-8");

  let fullText = "";
  const citedPages = new Set<number>();
  const pageRegex = /\[P(\d+)\]/g;

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

    const chunk = decoder.decode(value, { stream: true });
    fullText += chunk;

    if (onToken) {
      onToken(chunk);
    }

    // Inspect chunk for page citations
    let match: RegExpExecArray | null;
    while ((match = pageRegex.exec(chunk)) !== null) {
      citedPages.add(parseInt(match[1], 10));
    }
  }

  // Final check on complete text to catch citations split across chunk boundaries
  let finalMatch: RegExpExecArray | null;
  const finalRegex = /\[P(\d+)\]/g;
  while ((finalMatch = finalRegex.exec(fullText)) !== null) {
    citedPages.add(parseInt(finalMatch[1], 10));
  }

  return {
    fullText,
    citedPages: Array.from(citedPages).sort((a, b) => a - b)
  };
}

Front-End Integration: Clickable Page Jump Badges

Once parsed, transform markers like [P12] into interactive UI components. When an end user clicks [P12], trigger your client-side PDF viewer (such as PDF.js or an embedded viewer iframe) to navigate directly to page 12:

// Example helper converting citation tags to accessible links
function formatCitationsToHtml(markdownText) {
  return markdownText.replace(/\[P(\d+)\]/g, (match, pageNum) => {
    return `<button class="citation-badge" onclick="jumpToPdfPage(${pageNum})">Page ${pageNum}</button>`;
  });
}

Step 5: Document Lifecycle and Deletion

To maintain data hygiene, prevent orphaned files, and comply with security or GDPR retention requirements, remove documents when they are no longer needed.

Python Deletion Script

def delete_chatpdf_sources(source_ids: list[str], api_key: str) -> bool:
    url = "https://api.chatpdf.com/v1/sources/delete"
    headers = {
        "x-api-key": api_key,
        "Content-Type": "application/json"
    }
    payload = {"sources": source_ids}
    
    response = requests.post(url, headers=headers, json=payload)
    return response.status_code == 200

Integrate this endpoint into document removal routines, user account deactivations, or scheduled cleanup workers.


Complete End-to-End Workflow Example (Python)

Below is an end-to-end executable Python script demonstrating document upload, multi-turn dialogue with streaming, citation extraction, and cleanup:

import os
import re
import requests

API_KEY = os.environ.get("CHATPDF_API_KEY", "your_api_key_here")
HEADERS = {"x-api-key": API_KEY}

def run_document_intelligence_cycle(pdf_path: str):
    # 1. Ingest PDF Document
    print(f"Uploading {pdf_path} to ChatPDF...")
    with open(pdf_path, "rb") as f:
        files = [("file", (os.path.basename(pdf_path), f, "application/pdf"))]
        upload_res = requests.post("https://api.chatpdf.com/v1/sources/add-file", headers=HEADERS, files=files)
    
    upload_res.raise_for_status()
    source_id = upload_res.json()["sourceId"]
    print(f"Document indexed successfully. sourceId: {source_id}\n")

    try:
        # 2. Query with Streaming and Page Citations
        query_payload = {
            "sourceId": source_id,
            "stream": True,
            "referenceSources": True,
            "messages": [
                {
                    "role": "user",
                    "content": "Summarize the primary obligations of the contractor and identify where penalties apply."
                }
            ]
        }

        print("Querying endpoint with citation streaming enabled...\n--- Response Stream ---")
        chat_headers = {**HEADERS, "Content-Type": "application/json"}
        chat_res = requests.post(
            "https://api.chatpdf.com/v1/chats/message",
            headers=chat_headers,
            json=query_payload,
            stream=True
        )
        chat_res.raise_for_status()

        accumulated_text = ""
        for chunk in chat_res.iter_content(chunk_size=None, decode_unicode=True):
            if chunk:
                print(chunk, end="", flush=True)
                accumulated_text += chunk
        print("\n--- End of Stream ---\n")

        # 3. Extract Referenced Pages via Regex
        cited_pages = sorted(list(set(int(p) for p in re.findall(r'\[P(\d+)\]', accumulated_text))))
        print(f"Extracted Page References: {cited_pages}")

    finally:
        # 4. Cleanup Document Source
        print(f"\nCleaning up sourceId {source_id}...")
        del_res = requests.post(
            "https://api.chatpdf.com/v1/sources/delete",
            headers={**HEADERS, "Content-Type": "application/json"},
            json={"sources": [source_id]}
        )
        if del_res.status_code == 200:
            print("Document deleted successfully from ChatPDF storage.")
        else:
            print(f"Failed to delete document: {del_res.status_code}")

if __name__ == "__main__":
    # Ensure CHATPDF_API_KEY is set before running
    # run_document_intelligence_cycle("sample_contract.pdf")
    pass

Production Integration Guidelines and Engineering Caveats

To ensure your integration is robust under production load, implement the following operational safeguards:

1. Robust Rate Limiting and Backoff

ChatPDF does not expose a public real-time concurrency meter. Under traffic surges, requests may encounter HTTP 429 Too Many Requests. Wrap all API calls in an exponential backoff decorator (with jitter) that retries transient 429 and 5xx status codes.

2. Message History Window Trimming

Because the API limits history to 6 messages and 2,500 OpenAI tokens, maintain a sliding window on your application server. Strip out introductory pleasantries and only send the last 4 to 6 message exchanges. If prompt length risks truncation, employ a local token counter (such as tiktoken) to trim message history predictably rather than letting the remote server drop critical context.

3. Data Governance and Confidentiality

ChatPDF processes documents within its cloud infrastructure. If your organization handles strictly air-gapped data, HIPAA-restricted healthcare records, or contracts bound by extreme non-disclosure terms prohibiting third-party cloud processing, verify ChatPDF’s data privacy terms or consider an on-premises enterprise alternative. For typical commercial workflows, internal manuals, and standard legal documents, ChatPDF’s infrastructure provides standard enterprise encryption in transit and at rest.

4. Single-Document Boundary vs. Corpus-Wide Search

ChatPDF queries operate against a single sourceId. If your end users need to ask questions across an entire library of 5,000 PDFs at once, you will need an orchestration layer: first use an external metadata or BM25 index to identify the 1–3 most relevant documents, then query the corresponding sourceId instances.


Summary and Recommendation

For software teams building document-driven AI features, adopting ChatPDF's REST API is a high-leverage architectural decision. It eliminates the fragile operational mechanics of document chunking, vector embedding generation, and vector database hosting while delivering immediate streaming capabilities and verifiable page citations.

By following the ingestion, query streaming, and resource cleanup patterns detailed above, engineering teams can deliver a verified PDF question-answering system into production in hours rather than weeks.


References