API参考

一款用于从文档中提取结构化数据的REST API。发送一份文件,获取结构化的JSON返回。

REST APIJSON响应Webhook60多种语言

身份验证

所有请求都需要一个 X-API-Key 标头。从您Airparser账户的设置→API中获取您的密钥。

cURL
curl https://api.airparser.com/inboxes \
  -H "X-API-Key: YOUR_API_KEY"

请安全地存储您的API密钥——像对待密码一样对待它。

解析文档

上传任何文件,通过一次同步请求即可获取完全提取的数据——无需Webhook,无需轮询,无需二次调用。响应中包含所有提取字段的结构化JSON,可立即在您的工作流程中使用。

POST/inboxes/{inbox_id}/upload-syncAPI文档 →
curl \
  -X POST \
  https://api.airparser.com/inboxes/<INBOX_ID>/upload-sync \
  -F 'file=@./receipt.pdf' \
  -H "X-API-Key: <YOUR_API_KEY>"import requests

header = {"X-API-Key": "<API_KEY>"}
url = "https://api.airparser.com/inboxes/<INBOX_ID>/upload-sync"

with open('invoice.pdf', 'rb') as f:
    files = {'file': f}
    with requests.request("POST", url, files=files, headers=header) as response:
        print('response: ', response)const fetch = require("node-fetch");
const fs = require("fs");
const FormData = require("form-data");

const APIKEY = "<YOUR_API_KEY>";
const inboxId = "<INBOX_ID>";
const filePath = "/path/to/your/file.pdf";
const metadata = { foo: "bar" };

async function parseDocument(inboxId, filePath, metadata) {
  const url = `https://api.airparser.com/inboxes/${inboxId}/upload-sync`;

  const fileStream = fs.createReadStream(filePath);

  const form = new FormData();
  form.append("file", fileStream);
  form.append("meta", JSON.stringify(metadata));

  try {
    const response = await fetch(url, {
      method: "POST",
      body: form,
      headers: {
        "X-API-Key": APIKEY,
      },
    });

    const docId = await response.json();
    console.log(response.status);
    console.log("Document id:", docId);
  } catch (e) {
    console.error("Error:", e.message);
  }
}

parseDocument(inboxId, filePath, metadata);<?php

$apikey = '<API_KEY>';
$url = 'https://api.airparser.com/inboxes/<INBOX_ID>/upload-sync';
$filepath = './invoice.pdf';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'X-API-Key: ' . $apikey
));
curl_setopt($curl, CURLOPT_POST, true);

$meta = array(
  'foo' => 'bar',
  'my_id' => 42,
);
$metaJson = json_encode($meta);

curl_setopt($curl, CURLOPT_POSTFIELDS, array(
    'file' => curl_file_create($filepath, 'application/pdf', 'invoice.pdf'),
    'meta' => $metaJson
));

$response = curl_exec($curl);
curl_close($curl);

echo $response;
响应200 OK
{
  "doc_id": "64abc123def456...",
  "parsing_in_progress": false,
  "status": "parsed",
  "name": "invoice.pdf",
  "content_type": "application/pdf",
  "created_at": "2026-03-10T12:00:00.000Z",
  "processed_at": "2026-03-10T12:00:04.321Z",
  "json": {
    "invoice_number": "INV-001",
    "vendor": "Acme Corp",
    "total": 1250.00,
    "currency": "USD",
    "date": "2024-01-15"
  }
}

检索提取的数据

通过ID获取文档,查看其提取状态和结果。轮询此端点或使用Webhook来了解处理何时完成。

GET/documents/{document_id}
cURL
curl https://api.airparser.com/documents/doc_abc123 \
  -H "X-API-Key: YOUR_API_KEY"
响应200 OK
{
  "doc_id": "64abc123def456...",
  "parsing_in_progress": false,
  "status": "parsed",
  "name": "invoice.pdf",
  "content_type": "application/pdf",
  "created_at": "2026-03-10T12:00:00.000Z",
  "processed_at": "2026-03-10T12:00:04.321Z",
  "json": {
    "invoice_number": "INV-001",
    "vendor": "Acme Corp",
    "total": 1250.00,
    "date": "2024-01-15"
  }
}

定义提取模式(Schema)

定义要提取哪些字段。支持标量字段、列表(用于明细项)和枚举类型。

POST/inboxes/{inbox_id}/schema
{
  "fields": [
    {
      "type": "scalar",
      "data": {
        "name": "invoice_number",
        "description": "Invoice reference number",
        "type": "string",
        "default_value": ""
      }
    },
    {
      "type": "list",
      "data": {
        "name": "items",
        "description": "List of items in the invoice",
        "attributes": [
          {
            "name": "description",
            "description": "Item description",
            "type": "string",
            "default_value": ""
          },
          {
            "name": "amount",
            "description": "Item amount",
            "type": "decimal",
            "default_value": "0.00"
          }
        ]
      }
    },
    {
      "type": "enum",
      "data": {
        "name": "payment_status",
        "description": "Current payment status",
        "values": ["paid", "pending", "overdue"]
      }
    }
  ]
}

后处理

在数据发送到集成系统之前,对提取的数据运行Python代码。添加业务逻辑、合并字段、格式化数值。

合并字段
# Merge first and last name into full name
data['fullname'] = data['first_name'] + " " + data['last_name']

# Using f-strings (recommended)
data["fullname"] = f"{data['first_name']} {data['last_name']}"

# Using format() function
data['fullname'] = '{} {}'.format(data['first_name'], data['last_name'])
条件逻辑
# Only process invoices above certain amount
if float(data.get('total_amount', 0)) > 1000:
    data['priority'] = 'high'
else:
    data['priority'] = 'normal'

# Add timestamp
import datetime
data['processed_at'] = datetime.datetime.now().isoformat()

探索高级后处理技术和示例:

Webhook

提取完成后,Airparser会向您的端点发送一个 POST 请求。请使用 200 进行响应以确认收到。

设置步骤

  1. 1 从您的服务器或ngrok等服务复制您的Webhook端点URL。
  2. 2 在您的Airparser账户中前往集成→Webhook。
  3. 3 点击「创建Webhook」并粘贴您的端点URL。
  4. 4 使用示例文档测试Webhook,验证集成是否成功。
import json
from flask import Flask, request

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    payload = request.data
    data = json.loads(payload)

    # Process the parsed data
    # data contains all extracted fields

    return {'success': True}

if __name__ == '__main__':
    app.run(port=4242)const express = require('express');
const app = express();

app.post('/webhook', express.raw({type: 'application/json'}), (request, response) => {
  const payload = request.body;
  const data = JSON.parse(payload);

  // Process the parsed data
  // data contains all extracted fields

  // Return 200 to acknowledge receipt
  response.send();
});

app.listen(4242, () => console.log('Running on port 4242'));<?php
$payload = @file_get_contents('php://input');
$data = json_decode($payload, true);

// Process the parsed data
// $data contains all extracted fields

// Always return 200 to acknowledge receipt
http_response_code(200);
echo "OK";

资源

想要非技术性的概述?阅读 什么是文档提取API ——涵盖了概念、使用场景以及Airparser的API如何工作,不含代码示例。