AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Integrating the ChatPDF API: Automated Document Ingestion, Source ID Management, and Page Citation Extraction

Thiago Viana · 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 document question-answering systems often sends engineering teams down an expensive rabbit hole: managing document parsers, OCR pipelines, embedding models, vector databases, and complex reranking algorithms. The ChatPDF API (https://api.chatpdf.com/v1) bypasses this infrastructure burden entirely by providing a turnkey, REST-based Retrieval-Augmented Generation (RAG) backend. It delivers document parsing, conversational queries, and grounded page-level citations in a clean, developer-friendly interface.

At 365Finds, our commercial verdict is decisive: for teams building SaaS document assistants, legal contract parsers, research portals, or internal enterprise knowledge bases, ChatPDF API is the fastest and most cost-efficient route to market. You should choose it whenever verifiable page citations and rapid deployment matter more than fine-tuning bespoke embedding vectors. However, you must design your application architecture around its strict operational boundaries: a stateless chat model, a 6-message context ceiling, and document-level isolation.

This guide provides an end-to-end engineering blueprint to automate PDF ingestion, store and track source IDs, execute context-aware queries, extract structured citations, and safely clean up sources.


Technical Specifications and Prerequisites

Before sending API requests, obtain your secret API key from the ChatPDF developer portal. All HTTP requests require this key passed via a custom header:

x-api-key: sec_yourSecretApiKeyHere

Core API Constraints


1. Automated Document Ingestion Pipeline

To query any PDF, it must first be registered as a source. The ChatPDF API generates a persistent sourceId (formatted as src_xxxxxx), which serves as the unique handle for all subsequent interactions.

Option A: Ingest via Public URL (POST /v1/sources/add-url)

If your files are stored in public cloud storage (such as AWS S3 with pre-signed read access, Cloudflare R2, or a public CDN), use the URL endpoint. This offloads the file transfer bandwidth from your backend servers to ChatPDF.

Request:

POST /v1/sources/add-url HTTP/1.1
Host: api.chatpdf.com
x-api-key: sec_yourSecretApiKeyHere
Content-Type: application/json

{
  "url": "https://example.com/legal/master-services-agreement.pdf"
}

Response (HTTP 200 OK):

{
  "sourceId": "src_9aB2cD3eF4g5H6j7"
}

Option B: Ingest via Direct Binary File Upload (POST /v1/sources/add-file)

For documents uploaded directly by users through a web browser or stored on secure, air-gapped file systems, upload the binary stream using multipart/form-data. Only one file can be processed per request.

Request (cURL):

curl -X POST "https://api.chatpdf.com/v1/sources/add-file" \
  -H "x-api-key: sec_yourSecretApiKeyHere" \
  -F "file=@/local/path/quarterly-financial-report.pdf"

Node.js / TypeScript Example:

import axios from 'axios';
import FormData from 'form-data';
import fs from 'fs';

async function uploadLocalPdf(filePath: string, apiKey: string): Promise<string> {
  const form = new FormData();
  form.append('file', fs.createReadStream(filePath));

  const response = await axios.post<{ sourceId: string }>(
    'https://api.chatpdf.com/v1/sources/add-file',
    form,
    {
      headers: {
        'x-api-key': apiKey,
        ...form.getHeaders(),
      },
      maxBodyLength: Infinity,
    }
  );

  return response.data.sourceId;
}

365Finds Implementation Note: If a document has already been uploaded manually through the ChatPDF web interface (chatpdf.com/c/zNXgrtLfhbFw7KabJgE1), you do not need to re-upload it. You can interact with it via the API by prefixing the web ID with cha_ (e.g., cha_zNXgrtLfhbFw7KabJgE1).


2. Managing Source IDs in Application Architecture

Because the ChatPDF API is completely stateless and stores no metadata regarding your end users, tenants, or document hierarchies, your relational or document database must serve as the single source of truth.

Recommended Database Schema

When storing document references, track the following fields alongside your business objects:

Field NameTypePurpose
idUUID / StringInternal primary key for the document record
tenant_idUUID / StringMulti-tenant organization identifier
user_idUUID / StringID of the user who owns or uploaded the file
source_idStringChatPDF source identifier (src_... or cha_...)
original_filenameStringOriginal document name for UI presentation
page_countIntegerTotal pages (must remain <= 2,000)
statusEnumuploading, ready, failed, deleted
created_atTimestampIngestion timestamp for retention tracking
deleted_atTimestamp / NullNullable deletion flag for GDPR and cleanup pipelines
[Client Application] 
       │ 
       ▼
[Backend API Service] ─── (Uploads PDF) ───► [ChatPDF API (/v1/sources/add-file)]
       │                                                    │
       ├──── Stores { document_id, source_id, status } ─────┤ (Returns sourceId: "src_...")
       ▼                                                    │
[Internal PostgreSQL / MongoDB]                             │
       │                                                    │
       ▼ (User asks query)                                  ▼
[Backend API Service] ─── (POST /v1/chats/message) ──► [ChatPDF RAG Engine]

3. Querying Documents and Maintaining Stateless Conversations

The ChatPDF chat endpoint (POST /v1/chats/message) does not preserve conversational history on its servers. Every request must include the target sourceId and the entire conversation history within the messages array.

Single-Turn Query

{
  "sourceId": "src_9aB2cD3eF4g5H6j7",
  "messages": [
    {
      "role": "user",
      "content": "What is the termination notice period specified in Clause 14?"
    }
  ]
}

Multi-Turn Dialogue

To ask a follow-up question, your backend must assemble the recent exchanges in sequential order:

{
  "sourceId": "src_9aB2cD3eF4g5H6j7",
  "messages": [
    {
      "role": "user",
      "content": "What is the termination notice period specified in Clause 14?"
    },
    {
      "role": "assistant",
      "content": "Clause 14 specifies a 30-day written termination notice period."
    },
    {
      "role": "user",
      "content": "Are there any exceptions where notice is waived?"
    }
  ]
}

The 2,500-Token and 6-Message Boundary

ChatPDF enforces two hard limits on the messages payload:

  1. A maximum of 6 messages per request. Sending more than 6 will return an error or result in truncated analysis.
  2. A 2,500 OpenAI token context limit. If the cumulative token count of your conversation messages exceeds 2,500, ChatPDF automatically discards the oldest messages until the total falls under the ceiling.

365Finds Engineering Recommendation: Do not rely on ChatPDF's silent message pruning. Maintain conversation history in your application database (e.g., Redis or PostgreSQL) and implement a sliding window algorithm in your backend that truncates older dialogue turns before dispatching the payload.


4. Extracting and Parsing Page-Level Citations

One of ChatPDF's most compelling commercial advantages is verifiable grounding. In legal, regulatory, medical, and financial use cases, ungrounded AI answers introduce catastrophic liability. By enabling referenceSources: true, you force ChatPDF to output precise page attributions.

Citation Request Payload

{
  "referenceSources": true,
  "sourceId": "src_9aB2cD3eF4g5H6j7",
  "messages": [
    {
      "role": "user",
      "content": "What are the non-compete restrictions and where are they outlined?"
    }
  ]
}

Response Payload Structure

When referenceSources is set to true, the API returns two critical citation elements:

  1. Inline string tokens embedded directly inside content, using the format [P<N>] (e.g., [P4], [P18]).
  2. A structured references array containing individual page numbers:
{
  "content": "The employee is subject to a 12-month non-compete covenant [P4] covering North America, with specific exclusions for existing freelance engagements [P18].",
  "references": [
    { "pageNumber": 4 },
    { "pageNumber": 18 }
  ]
}

UI Parsing and Deep-Linking Pattern

To convert raw text markers into clickable interactive elements in a frontend viewer (such as React PDF, PDF.js, or standard web viewers), transform [P<N>] tokens into actionable components:

// Citation parsing utility
interface CitationSegment {
  type: 'text' | 'citation';
  value: string;
  pageNumber?: number;
}

export function parseChatPDFCitations(rawContent: string): CitationSegment[] {
  const citationRegex = /\[P(\d+)\]/g;
  const segments: CitationSegment[] = [];
  let lastIndex = 0;
  let match: RegExpExecArray | null;

  while ((match = citationRegex.exec(rawContent)) !== null) {
    if (match.index > lastIndex) {
      segments.push({
        type: 'text',
        value: rawContent.slice(lastIndex, match.index),
      });
    }

    segments.push({
      type: 'citation',
      value: match[0],
      pageNumber: parseInt(match[1], 10),
    });

    lastIndex = citationRegex.lastIndex;
  }

  if (lastIndex < rawContent.length) {
    segments.push({
      type: 'text',
      value: rawContent.slice(lastIndex),
    });
  }

  return segments;
}

When rendered, a user clicking on [P4] can trigger your embedded PDF viewer to execute:

pdfViewerInstance.navigateToPage(citation.pageNumber);

5. Document Lifecycle Management and Safe Deletion

Failing to delete stale documents causes orphan resource bloat, introduces compliance vulnerabilities (GDPR right-to-erasure violations), and risks data leakage across multi-tenant boundaries.

The ChatPDF API provides a dedicated batch deletion endpoint:

POST /v1/sources/delete HTTP/1.1
Host: api.chatpdf.com
x-api-key: sec_yourSecretApiKeyHere
Content-Type: application/json

{
  "sources": [
    "src_9aB2cD3eF4g5H6j7",
    "src_1xY2zA3bC4d5E6f7"
  ]
}

Response (HTTP 200 OK):

{}

An empty HTTP 200 response indicates successful permanent deletion.

Recommended Lifecycle Automation Patterns

  1. User-Triggered Cleanup: When a tenant or end-user deletes a document in your application, fire an asynchronous deletion job against /v1/sources/delete and update the local database status to deleted.
  2. Ephemeral Document TTL: For customer support chatbots where documents are only relevant during an active session, schedule automated cleanup tasks via Redis BullMQ or Celery after a 24-hour inactivity window.
  3. Graceful Batching: When offboarding an organization, collect all associated sourceId values and transmit them in batches of 50 to 100 within a single /v1/sources/delete call.

Complete End-to-End Integration Example (Node.js & TypeScript)

Here is a production-grade service class combining ingestion, cited querying, and cleanup:

import axios, { AxiosInstance } from 'axios';
import FormData from 'form-data';
import fs from 'fs';

export class ChatPdfClient {
  private client: AxiosInstance;

  constructor(apiKey: string) {
    this.client = axios.create({
      baseURL: 'https://api.chatpdf.com/v1',
      headers: {
        'x-api-key': apiKey,
      },
    });
  }

  // 1. Upload via Public URL
  async addSourceFromUrl(url: string): Promise<string> {
    const response = await this.client.post<{ sourceId: string }>('/sources/add-url', { url });
    return response.data.sourceId;
  }

  // 2. Upload via Local File Stream
  async addSourceFromFile(filePath: string): Promise<string> {
    const form = new FormData();
    form.append('file', fs.createReadStream(filePath));

    const response = await this.client.post<{ sourceId: string }>('/sources/add-file', form, {
      headers: form.getHeaders(),
      maxBodyLength: Infinity,
    });
    return response.data.sourceId;
  }

  // 3. Send Message with Grounded Page Citations
  async askDocument(
    sourceId: string,
    prompt: string,
    history: Array<{ role: 'user' | 'assistant'; content: string }> = []
  ): Promise<{ content: string; references: Array<{ pageNumber: number }> }> {
    const messages = [...history.slice(-4), { role: 'user' as const, content: prompt }];

    const response = await this.client.post<{
      content: string;
      references: Array<{ pageNumber: number }>;
    }>('/chats/message', {
      sourceId,
      messages,
      referenceSources: true,
    });

    return response.data;
  }

  // 4. Batch Delete Sources
  async deleteSources(sourceIds: string[]): Promise<void> {
    if (sourceIds.length === 0) return;
    await this.client.post('/sources/delete', {
      sources: sourceIds,
    });
  }
}

365Finds Institutional Evaluation: Trade-Offs & Strategic Fit

When deciding whether to adopt the ChatPDF API or build an in-house RAG architecture, evaluate these critical trade-offs:

Evaluation DimensionChatPDF APICustom In-House RAG Pipeline
Time to MarketHours (instant REST endpoints)Weeks to months (data ingestion, chunking, vector DB)
Operational OverheadZero infrastructure; managed indexingHigh (monitoring embeddings, vector drift, DB clusters)
Citation ReliabilityBuilt-in page attribution ([P#] and pageNumber)Manual metadata mapping required across chunks
Cross-Document QueryingSingle sourceId per chat requestFull cross-document search across entire vector collections
Model CustomizationLocked to ChatPDF managed model pipelineFull control over LLM choice, chunk size, and reranker
Data Residency / On-PremHosted third-party cloudCan be deployed strictly inside VPC or on-premise

Our Recommendation


References