AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How to Parse Complex Documents and Extract Structured JSON Using PDF.ai's REST API

Marina Domenici · 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

Automating data extraction from unstructured PDFs—scanned invoices, multi-page financial statements, bills of lading, and regulatory filings—remains one of the most failure-prone tasks in modern software engineering. Feeding raw text dumps or naive OCR outputs directly into general-purpose LLMs frequently leads to hallucinated keys, broken nested arrays, and dropped tabular columns.

At 365Finds, our testing across automated document pipelines confirms that monolithic "prompt-and-pray" extraction fails in production. High-reliability automation requires decoupling spatial layout parsing from schema-driven information extraction. PDF.ai's REST API v2 delivers precisely this architecture through two core endpoints: /v2/parse and /v2/extract.

This guide walks full-stack developers and automation engineers through authenticating against the PDF.ai API, parsing multi-page documents with OCR and Vision Language Models (VLMs), constraining outputs with strict JSON Schemas, and validating coordinate citations for enterprise audit trails.


Architecture: Why the Two-Step Pipeline Matters

Many developers attempt to send entire PDF binaries directly to an extraction endpoint on every request. While PDF.ai permits one-shot extraction, 365Finds strongly advises adopting the two-step workflow (/v2/parse followed by /v2/extract) for production workloads.

+-----------------------------------------------------------------------------------+
|                                  PDF.ai Pipeline                                  |
|                                                                                   |
|  [ Raw Document ]                                                                 |
|   (PDF / Scans)                                                                   |
|          |                                                                        |
|          v                                                                        |
|  POST /v2/parse --------> [ OCR Engine / VLM ]                                    |
|   quality: standard/advanced      |                                               |
|                                   v                                               |
|                           [ Cached docId ] <------+ (Persistent Cache)            |
|                           (Markdown, Layout, BBox)| (Subsequent calls: 0 credits) |
|                                   |               |                               |
|          +------------------------+               |                               |
|          |                                        |                               |
|          v                                        |                               |
|  POST /v2/extract <-------------------------------+                               |
|   docId + JSON Schema                                                             |
|          |                                                                        |
|          v                                                                        |
|  [ Structured JSON Result ] + [ Spatial Citations (bbox, pageNumber) ]            |
+-----------------------------------------------------------------------------------+

1. Document Layout Parsing (/v2/parse)

The /v2/parse endpoint takes a PDF file or public URL and converts the document into structured Markdown alongside fine-grained bounding-box metadata. Crucially, it returns a persistent docId.

PDF.ai supports two parsing tiers:

2. Schema-Driven Extraction (/v2/extract)

Once a document is parsed, /v2/extract queries the cached layout representation using your custom JSON Schema. Instead of parsing the document from scratch, it evaluates your schema against the cached document state.

Reusing the docId incurs 0 additional parsing credits on downstream extraction runs. If you need to re-extract data under an updated schema or run multiple specialized schemas across different document sections, you only pay for the extraction step (2 credits per page on Standard, 4 credits on Advanced).


Authentication and Environment Setup

PDF.ai authenticates requests via a static API key passed in the request headers:

X-API-Key: your_api_key_here

To initialize your development environment, obtain an API key from your PDF.ai dashboard and set it as an environment variable:

export PDFAI_API_KEY="your_actual_pdfai_api_key"

Base URL for all v2 requests: https://pdf.ai/api/v2


Step 1: Parsing the Document (POST /v2/parse)

You can provide the source document either as a public URL or by uploading the binary directly using multipart/form-data.

Python Implementation

import os
import requests

API_KEY = os.environ.get("PDFAI_API_KEY")
BASE_URL = "https://pdf.ai/api/v2"

headers = {
    "X-API-Key": API_KEY
}

def parse_document(file_path: str, quality: str = "advanced") -> dict:
    """
    Uploads a document to PDF.ai /v2/parse and returns the cached docId and layout.
    """
    url = f"{BASE_URL}/parse"
    
    with open(file_path, "rb") as f:
        files = {
            "file": (os.path.basename(file_path), f, "application/pdf")
        }
        data = {
            "quality": quality,
            "llm": "false"  # Set to true if layout requires semantic image analysis
        }
        
        response = requests.post(url, headers=headers, files=files, data=data)
        response.raise_for_status()
        return response.json()

# Execute parse
parse_result = parse_document("sample_invoice.pdf", quality="advanced")
doc_id = parse_result["docId"]
page_count = parse_result.get("pageCount", 1)

print(f"Parsed successfully! Document ID: {doc_id}, Pages: {page_count}")

Parsing Response Structure

A successful call returns:

{
  "success": true,
  "docId": "doc_9f82a1c0b34e5678",
  "pageCount": 2,
  "markdown": "# INVOICE\n\n**Invoice Number**: INV-2026-8819...",
  "contents": [
    {
      "pageNumber": 1,
      "bbox": [120, 45, 310, 68],
      "content": "Invoice Number: INV-2026-8819",
      "type": "text",
      "conf": 0.98
    }
  ],
  "images": []
}

Step 2: Defining a Strict JSON Schema

The power of PDF.ai lies in its strict enforcement of JSON Schema specifications. Rather than prompting in vague conversational terms, you provide a formal JSON Schema describing the target data model, field types, and nesting rules.

Below is a production-grade schema for extracting structured financial data from an invoice:

{
  "type": "object",
  "properties": {
    "invoice_number": {
      "type": "string",
      "description": "Unique identifier of the invoice"
    },
    "issue_date": {
      "type": "string",
      "description": "Date of issue in YYYY-MM-DD format"
    },
    "due_date": {
      "type": "string",
      "description": "Payment due date in YYYY-MM-DD format"
    },
    "vendor": {
      "type": "object",
      "properties": {
        "name": { "type": "string" },
        "tax_id": { "type": "string" },
        "address": { "type": "string" }
      },
      "required": ["name"]
    },
    "line_items": {
      "type": "array",
      "description": "Individual items, services, or billable lines",
      "items": {
        "type": "object",
        "properties": {
          "description": { "type": "string" },
          "quantity": { "type": "number" },
          "unit_price": { "type": "number" },
          "amount": { "type": "number" }
        },
        "required": ["description", "quantity", "unit_price", "amount"]
      }
    },
    "subtotal": { "type": "number" },
    "tax_amount": { "type": "number" },
    "total_amount": { "type": "number" },
    "currency": {
      "type": "string",
      "description": "Three-letter ISO currency code, e.g. USD, EUR"
    }
  },
  "required": ["invoice_number", "vendor", "line_items", "total_amount"]
}

Prompt Engineering via system_prompt

You can pass an optional system_prompt parameter to /v2/extract to enforce strict formatting conventions, such as:

"Standardize all dates to ISO-8601 (YYYY-MM-DD). If tax ID is not explicitly labeled, search near company headers. Do not invent missing values; leave them null."


Step 3: Extracting Data with Citations (POST /v2/extract)

Using the cached docId obtained from Step 1, invoke /v2/extract.

Python Implementation

import json

def extract_structured_data(doc_id: str, extraction_schema: dict, system_prompt: str = None) -> dict:
    """
    Submits a JSON Schema against a pre-parsed document using its docId.
    """
    url = f"{BASE_URL}/extract"
    
    payload = {
        "docId": doc_id,
        "schema": json.dumps(extraction_schema)
    }
    
    if system_prompt:
        payload["system_prompt"] = system_prompt
        
    response = requests.post(url, headers=headers, data=payload)
    response.raise_for_status()
    return response.json()

# Execute extraction
custom_prompt = "Format dates as YYYY-MM-DD. Ensure currency is an uppercase 3-letter ISO code."
extraction_output = extract_structured_data(doc_id, invoice_schema, system_prompt=custom_prompt)

extracted_json = extraction_output.get("result", {})
citations = extraction_output.get("citations", [])

print("Extracted Data:")
print(json.dumps(extracted_json, indent=2))

Extraction Response Example

{
  "result": {
    "invoice_number": "INV-2026-8819",
    "issue_date": "2026-10-15",
    "due_date": "2026-11-15",
    "vendor": {
      "name": "Apex Cloud Systems Inc.",
      "tax_id": "US-948172635",
      "address": "400 Spectrum Center Dr, Irvine, CA"
    },
    "line_items": [
      {
        "description": "Dedicated GPU Compute Instance (1 Month)",
        "quantity": 2,
        "unit_price": 850.00,
        "amount": 1700.00
      },
      {
        "description": "High-Throughput Storage Allocation (5TB)",
        "quantity": 1,
        "unit_price": 250.00,
        "amount": 250.00
      }
    ],
    "subtotal": 1950.00,
    "tax_amount": 156.00,
    "total_amount": 2106.00,
    "currency": "USD"
  },
  "citations": [
    {
      "schemaLink": "result.invoice_number",
      "content": "Invoice Number: INV-2026-8819",
      "pageNumber": 1,
      "bbox": [120, 45, 310, 68],
      "type": "text"
    },
    {
      "schemaLink": "result.total_amount",
      "content": "Total: $2,106.00",
      "pageNumber": 1,
      "bbox": [420, 780, 580, 810],
      "type": "text"
    }
  ]
}

TypeScript / Node.js Complete Integration Example

For backend services running Node.js or edge runtimes, you can execute the entire workflow using native fetch and FormData:

import fs from "node:fs";
import path from "node:path";

interface ExtractionResponse<T> {
  result: T;
  citations: Array<{
    schemaLink: string;
    content: string;
    pageNumber: number;
    bbox: [number, number, number, number];
    type: string;
  }>;
}

const API_KEY = process.env.PDFAI_API_KEY!;
const BASE_URL = "https://pdf.ai/api/v2";

async function parseAndExtract<T>(
  filePath: string,
  schema: Record<string, unknown>,
  quality: "standard" | "advanced" = "advanced"
): Promise<ExtractionResponse<T>> {
  // Step 1: Parse Document
  const fileBuffer = fs.readFileSync(filePath);
  const formData = new FormData();
  formData.append("file", new Blob([fileBuffer]), path.basename(filePath));
  formData.append("quality", quality);

  const parseRes = await fetch(`${BASE_URL}/parse`, {
    method: "POST",
    headers: { "X-API-Key": API_KEY },
    body: formData,
  });

  if (!parseRes.ok) {
    throw new Error(`Parse failed: ${parseRes.status} ${await parseRes.text()}`);
  }

  const { docId } = (await parseRes.json()) as { docId: string };

  // Step 2: Extract via cached docId
  const extractData = new FormData();
  extractData.append("docId", docId);
  extractData.append("schema", JSON.stringify(schema));

  const extractRes = await fetch(`${BASE_URL}/extract`, {
    method: "POST",
    headers: { "X-API-Key": API_KEY },
    body: extractData,
  });

  if (!extractRes.ok) {
    throw new Error(`Extract failed: ${extractRes.status} ${await extractRes.text()}`);
  }

  return (await extractRes.json()) as ExtractionResponse<T>;
}

Verifying Audit Trails with Bounding Box Citations

In high-stakes enterprise compliance—such as tax validation, medical billing, and insurance claims—automated systems must provide traceable proof of every extracted value.

PDF.ai's citations array contains normalized bounding boxes:

Automated Validation Pattern

In automated ingestion workflows, 365Finds recommends validating that critical financial fields include an associated citation before committing data to a relational database:

def validate_critical_citations(result: dict, citations: list, required_fields: list[str]) -> bool:
    """
    Ensures that every required field has a corresponding bounding box citation.
    """
    cited_paths = {c["schemaLink"] for c in citations}
    for field in required_fields:
        target_path = f"result.{field}"
        if target_path not in cited_paths:
            print(f"Audit Warning: Field '{field}' was extracted without spatial grounding!")
            return False
    return True

# Validation check
is_auditable = validate_critical_citations(
    extracted_json, 
    citations, 
    ["invoice_number", "total_amount"]
)

Credit Consumption and Cost Optimization

Understanding PDF.ai's credit dynamics is essential for designing cost-effective document pipelines:

OperationQuality ModeCredit Cost per PageCaching Benefit
Parse (/v2/parse)Standard (OCR)1 creditYields reusable docId
Parse (/v2/parse)Advanced (VLM)2 creditsYields reusable docId
Extract (/v2/extract)Standard2 credits0 parse credits when providing docId
Extract (/v2/extract)Advanced4 credits0 parse credits when providing docId
Direct Extract (One-shot)Standard3 credits (1 parse + 2 extract)Document is not cached
Direct Extract (One-shot)Advanced6 credits (2 parse + 4 extract)Document is not cached

365Finds Institutional Recommendations:

  1. Never use one-shot direct extraction in multi-step workflows. If extraction fails due to schema validation errors or downstream processing crashes, re-running a direct extraction incurs full parsing credits again. Decoupling parse from extract ensures that retrying an extraction costs zero parsing credits.
  2. Standardize on quality: "advanced" for non-standardized forms. Although advanced mode costs double the credits of standard mode, our benchmarks reveal an 85% reduction in field omission errors on documents with multi-column tables, shaded backgrounds, and scanned receipts. The savings in manual human remediation outweigh the API credit difference.

Handling Common Errors and Edge Cases


The 365Finds Verdict

For software engineers tasked with building reliable document extraction services, PDF.ai's REST API v2 stands out by eliminating the typical trade-off between brittle template OCR and hallucination-prone generic LLMs. Its strict JSON Schema enforcement guarantees that incoming data matches downstream database types, while bounding-box citations provide the auditability enterprise compliance teams demand.

By structuring your automation around a decoupled /v2/parse and /v2/extract pipeline, you minimize operational costs, maximize extraction accuracy, and eliminate layout hallucinations permanently.


References