Convert PDF to Markdown in Python
A step-by-step tutorial using the REST API: get a key, create a job, poll, and download clean Markdown – with a full, copyable example and proper error handling.
Check the output, then use it
Use the live OpenAPI contract. Check HTTP failures, queued/processing/ready/error, a polling deadline and truncated before downloading. Keep API keys server-side.
Server processing; temporary results. Review numbers and OCR mistakes against the original.
One key, three calls
To convert a PDF to Markdown in Python you call a small REST API with a bearer key: POST /api/v2/jobs to create a job, GET /api/v2/jobs/{id} to poll until it is ready, then GET /api/v2/jobs/{id}/download for the Markdown. There is nothing to host and no heavy library to install – just requests. The same lifecycle is exposed as a hosted MCP for agents, and the output is the same Markdown the extension and web app produce, so you can prototype in the browser and then automate with confidence.
Set up in four steps
Get an API key
Sign in with a free Google account and create an API key in your account; it is shown once. Send it as Authorization: Bearer p2m_your_key.
Create a job
POST the PDF URL (or uploaded bytes) to /api/v2/jobs. You get back a job id and a status.
Poll until ready
GET /api/v2/jobs/{id} until status is ready or error.
Download the Markdown
GET /api/v2/jobs/{id}/download for the Markdown text. Honor truncated and pages.
The complete Python script
Standard library plus requests. Create from a PDF URL, poll, then save the Markdown.
import os, time
from pathlib import Path
import requests
API = "https://pdf2md.dev/api/v2"
H = {"Authorization": "Bearer " + os.environ["P2M_API_KEY"]}
def call(method, path, **kwargs):
for attempt in range(4):
r = requests.request(method, API + path, headers=H, timeout=30, **kwargs)
if r.status_code != 429:
r.raise_for_status()
return r
if attempt == 3:
r.raise_for_status()
try:
delay = float(r.headers.get("Retry-After", "3"))
except ValueError:
delay = 3
if delay > 60:
raise RuntimeError("Retry later: rate limit")
time.sleep(max(1, delay))
# URL must point to a publicly accessible PDF, not an HTML document viewer.
created = call("POST", "/jobs", json={
"url": os.environ.get("PDF_URL", "https://example.com/document.pdf"),
"options": {"image_mode": "placeholder", "ocr_lang": "en"}
}).json()
jid = created["job_id"]
deadline = time.monotonic() + 20 * 60
while True:
job = call("GET", f"/jobs/{jid}").json()
if job["status"] == "ready":
break
if job["status"] in ("error", "canceled", "deleted"):
raise RuntimeError(f"Job ended: {job['status']} {job.get('error_code', '')}")
if time.monotonic() >= deadline:
raise TimeoutError("Polling deadline reached; the job may still be running")
time.sleep(3)
md = call("GET", f"/jobs/{jid}/download").text
if job.get("truncated"):
print("WARNING: partial result; verify missing pages")
Path("document.md").write_text(md, encoding="utf-8")
Uploading a local file instead of a URL? POST the bytes as multipart/form-data with a file field to the same endpoint. The full request and response shapes are in the OpenAPI spec.
To convert many PDFs, create one job per file and poll them in parallel up to your slot limit (3 on the free tier, more on paid). Keep a distinct Idempotency-Key per file so retries never duplicate work, and back off on 429 using the Retry-After header.
Errors, retries and webhooks
Read the error code
A failed job returns status: error with a machine-readable error_code (processing_timeout or conversion_failed) and a safe error_message – branch on the code, not the text.
Handle truncated
A long document can come back ready with truncated=true. Check the flag and split the file or use a longer paid budget.
Idempotency-Key
Send an Idempotency-Key header so a retried create returns the same job instead of duplicating work.
Webhooks over polling
On paid tiers, register a webhook or pass callback_url and get a POST on ready/error instead of polling.
Respect 429
On 429, wait for the Retry-After seconds before retrying; do not hammer the queue.
Keep keys server-side
The key is a secret: store it server-side, send over TLS, and rotate or revoke it any time.
Not on Python? Same three calls
It is a plain HTTPS API, so any language works. The same create / poll / download in Node:
// Node 18+. Keep P2M_API_KEY in the server environment, never in a web page.
import { writeFile } from 'node:fs/promises';
const API = 'https://pdf2md.dev/api/v2';
const key = process.env.P2M_API_KEY;
if (!key) throw new Error('Set P2M_API_KEY');
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
async function request(path, options = {}) {
for (let attempt = 0; attempt < 4; attempt++) {
const r = await fetch(API + path, {
...options,
headers: { Authorization: 'Bearer ' + key, ...options.headers },
signal: AbortSignal.timeout(30000),
});
if (r.status === 429 && attempt < 3) {
const delay = Number(r.headers.get('Retry-After') || 3);
if (!Number.isFinite(delay) || delay > 60) throw new Error('Rate limited; retry later');
await pause(Math.max(1, delay) * 1000);
continue;
}
if (!r.ok) throw new Error('HTTP ' + r.status + ': ' + (await r.text()).slice(0, 300));
return r;
}
}
const created = await (await request('/jobs', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ url: process.env.PDF_URL || 'https://example.com/document.pdf',
options: { image_mode: 'placeholder', ocr_lang: 'en' } }),
})).json();
if (!created.job_id) throw new Error('Missing job_id');
const deadline = Date.now() + 20 * 60 * 1000;
let job;
while (true) {
job = await (await request('/jobs/' + created.job_id)).json();
if (job.status === 'ready') break;
if (['error', 'canceled', 'deleted'].includes(job.status)) throw new Error('Job ended: ' + job.status);
if (Date.now() >= deadline) throw new Error('Polling deadline reached; the job may still be running');
await pause(3000);
}
const md = await (await request('/jobs/' + created.job_id + '/download')).text();
if (job.truncated) console.warn('Partial result; verify missing pages');
await writeFile('document.md', md, 'utf8');
Prefer agent tools or RAG?
The same lifecycle is a hosted MCP for ChatGPT, Claude and agent frameworks. For ingestion and chunking, see the RAG guide.
Common questions
How do I convert a PDF to Markdown in Python?
Call the REST API with a bearer key: POST the PDF to /api/v2/jobs, poll GET /api/v2/jobs/{id} until ready, then GET the /download for the Markdown. The full requests example is above.
Do I need an API key?
Yes for the API. A free Google account lets you create a key and use the hosted MCP. The browser extension and web app stay anonymous and need no key.
How do I handle errors and timeouts?
A failed job returns status: error with a machine-readable error_code (processing_timeout or conversion_failed) and a safe error_message. A long document can come back ready with truncated=true; check that flag.
Can I avoid polling?
On paid tiers, register a webhook or pass callback_url when creating the job, and the service POSTs you on ready or error so you do not poll.
Does it work from Node or other languages?
Yes. It is a plain HTTPS API, so any language works. A short Node example is above, and the full contract is in the OpenAPI spec.
How do I convert a local file instead of a URL?
POST the file bytes as multipart/form-data with a file field to /api/v2/jobs, instead of a JSON body with a url. The poll and download steps are identical.
Can I convert many PDFs at once?
Create a job per file and poll them in parallel up to your slot limit (3 on the free tier, more on paid). Paid tiers add a batch-create endpoint and webhooks so you do not poll at all.
Is the output the same as the extension and web app?
Yes. Every surface uses the same conversion engine, so the API returns the same Markdown you would get in the browser.
Is it free?
The free tier gives 3 slots, 10 MB files, a 15-minute time budget and 1-hour retention. Paid tiers raise every limit and add webhooks and batch create.
Docling PDF to Markdown
Docling is an optional engine: set options.engine to docling. Test on representative digital PDFs. MinerU is the default. Compare the result with the original; Docling can fail at its time limit rather than return a partial result.