Recipes
A MarkItDown API server with FastAPI
If you put MarkItDown behind an HTTP endpoint, four things matter more than the conversion call: a size limit, an allow-list of file types, converting from the uploaded bytes instead of a path or URL, and a timeout. This is a 40-line service with all four, and the curl runs that show how it behaves.
Short answer
Convert from the uploaded bytes with convert_stream, give it the file extension yourself, cap the upload size and the time, and accept only the types you need. The full service is below.
Tested with markitdown 0.1.9 · Python 3.13 · FastAPI 0.163.1 · uvicorn 0.54.0 · markitdown 0.1.9 · Linux lab; run locally, not in Docker (T23) · 2026-11-16 · evidence: api-server.log, api-server-app.py
The service
"""A small upload-to-Markdown API around MarkItDown: size limit, extension allow-list, stream conversion, a timeout, and no URL inputs."""
import asyncio, io, os
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI, File, HTTPException, UploadFile
from markitdown import MarkItDown, StreamInfo
MAX_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", 10 * 1024 * 1024))
ALLOWED = {".docx", ".xlsx", ".pptx", ".pdf", ".csv", ".html", ".epub"}
TIMEOUT_SECONDS = float(os.getenv("CONVERT_TIMEOUT", 60))
app = FastAPI(title="markitdown-api")
md = MarkItDown(enable_plugins=False) # one converter, plugins off
pool = ThreadPoolExecutor(max_workers=2) # conversions are CPU-bound: keep this small
@app.post("/convert")
async def convert(file: UploadFile = File(...)):
ext = os.path.splitext(file.filename or "")[1].lower()
if ext not in ALLOWED:
raise HTTPException(415, f"File type {ext or '(none)'} is not allowed")
data = await file.read(MAX_BYTES + 1) # never read more than the limit
if len(data) > MAX_BYTES:
raise HTTPException(413, f"File is larger than {MAX_BYTES} bytes")
loop = asyncio.get_running_loop()
job = loop.run_in_executor(pool, lambda: md.convert_stream(io.BytesIO(data), stream_info=StreamInfo(extension=ext)).markdown)
try:
text = await asyncio.wait_for(job, TIMEOUT_SECONDS)
except asyncio.TimeoutError:
raise HTTPException(504, "Conversion took too long")
except Exception as e: # do not leak internals
raise HTTPException(422, f"Could not convert this file ({type(e).__name__})")
return {"filename": file.filename, "characters": len(text), "markdown": text}
@app.get("/health")
def health(): return {"ok": True}
"""A small upload-to-Markdown API around MarkItDown: size limit, extension allow-list, stream conversion, a timeout, and no URL inputs.""" import asyncio, io, os from concurrent.futures import ThreadPoolExecutor from fastapi import FastAPI, File, HTTPException, UploadFile from markitdown import MarkItDown, StreamInfo
MAX_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", 10 * 1024 * 1024)) ALLOWED = {".docx", ".xlsx", ".pptx", ".pdf", ".csv", ".html", ".epub"} TIMEOUT_SECONDS = float(os.getenv("CONVERT_TIMEOUT", 60))
app = FastAPI(title="markitdown-api") md = MarkItDown(enable_plugins=False) # one converter, plugins off pool = ThreadPoolExecutor(max_workers=2) # conversions are CPU-bound: keep this small
@app.post("/convert") async def convert(file: UploadFile = File(...)): ext = os.path.splitext(file.filename or "")[1].lower() if ext not in ALLOWED: raise HTTPException(415, f"File type {ext or '(none)'} is not allowed") data = await file.read(MAX_BYTES + 1) # never read more than the limit if len(data) > MAX_BYTES: raise HTTPException(413, f"File is larger than {MAX_BYTES} bytes") loop = asyncio.get_running_loop() job = loop.run_in_executor(pool, lambda: md.convert_stream(io.BytesIO(data), stream_info=StreamInfo(extension=ext)).markdown) try: text = await asyncio.wait_for(job, TIMEOUT_SECONDS) except asyncio.TimeoutError: raise HTTPException(504, "Conversion took too long") except Exception as e: # do not leak internals raise HTTPException(422, f"Could not convert this file ({type(e).name})") return {"filename": file.filename, "characters": len(text), "markdown": text}
@app.get("/health") def health(): return {"ok": True}
Run it with uvicorn app:app. It needs fastapi, uvicorn, python-multipart and markitdown with the extras you allow.
What it did
# T23 API server recipe (FastAPI), tests with curl
date: 2026-11-16
fastapi 0.163.1
markitdown 0.1.9
uvicorn 0.54.0
$ curl -s localhost:8099/health
{"ok":true}
$ curl -s -w ' [%{http_code} in %{time_total}s]' -F file=@/home/user/MarkItDown/public/samples/report.docx localhost:8099/convert
{"filename":"report.docx","characters":838,"markdown":"Pilot Report: Field Station Alpha\n\n# 1. Summary\n\nThis report covers **three sites** during *spring 2026* <u>with underlined</u> ~~and struck text.~~\n\n## 1.1 Key findings\n\n* Rainfall rose 12% year o
$ curl -s -w ' [%{http_code} in %{time_total}s]' -F file=@/home/user/MarkItDown/public/samples/pdf-text.pdf localhost:8099/convert
{"filename":"pdf-text.pdf","characters":926,"markdown":"Pilot Report: Field Station Alpha\n\n1. Summary\nRainfall across the three stations rose steadily through the spring. Sensors reported every ten\nminutes and the readings were averaged per day. Rainfall a
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/public/samples/unsupported.gif localhost:8099/convert
{"detail":"File type .gif is not allowed"} [415]
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/lab/corpus/synthetic/report.rtf localhost:8099/convert
{"detail":"File type .rtf is not allowed"} [415]
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/public/samples/pdf-encrypted.pdf localhost:8099/convert
{"detail":"Could not convert this file (FileConversionException)"} [422]
$ curl -s -w ' [%{http_code}]' -F 'file=@/home/user/MarkItDown/lab/corpus/synthetic/pdf-200-pages.pdf' localhost:8099/convert
{"filename":"pdf-200-pages.pdf","characters":375091,"markdown":"Section 1\nRainfall across the three stations rose steadily through the spring. Sensors reported every ten\nminutes and the readings were averaged per day. Rainfall across the three stations rose
$ curl -s -w ' [%{http_code}]' -F file=@/tmp/big.pdf localhost:8099/convert
{"detail":"File is larger than 10485760 bytes"} [413]
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/public/samples/pdf-scanned.pdf localhost:8099/convert
{"filename":"pdf-scanned.pdf","characters":0,"markdown":""} [200]
T23 API server recipe (FastAPI), tests with curl
date: 2026-11-16 fastapi 0.163.1 markitdown 0.1.9 uvicorn 0.54.0
$ curl -s localhost:8099/health {"ok":true}
$ curl -s -w ' [%{http_code} in %{time_total}s]' -F file=@/home/user/MarkItDown/public/samples/report.docx localhost:8099/convert
{"filename":"report.docx","characters":838,"markdown":"Pilot Report: Field Station Alpha\n\n# 1. Summary\n\nThis report covers three sites during spring 2026 <u>with underlined</u> and struck text.\n\n## 1.1 Key findings\n\n* Rainfall rose 12% year o
$ curl -s -w ' [%{http_code} in %{time_total}s]' -F file=@/home/user/MarkItDown/public/samples/pdf-text.pdf localhost:8099/convert {"filename":"pdf-text.pdf","characters":926,"markdown":"Pilot Report: Field Station Alpha\n\n1. Summary\nRainfall across the three stations rose steadily through the spring. Sensors reported every ten\nminutes and the readings were averaged per day. Rainfall a
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/public/samples/unsupported.gif localhost:8099/convert {"detail":"File type .gif is not allowed"} [415]
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/lab/corpus/synthetic/report.rtf localhost:8099/convert {"detail":"File type .rtf is not allowed"} [415]
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/public/samples/pdf-encrypted.pdf localhost:8099/convert {"detail":"Could not convert this file (FileConversionException)"} [422]
$ curl -s -w ' [%{http_code}]' -F 'file=@/home/user/MarkItDown/lab/corpus/synthetic/pdf-200-pages.pdf' localhost:8099/convert {"filename":"pdf-200-pages.pdf","characters":375091,"markdown":"Section 1\nRainfall across the three stations rose steadily through the spring. Sensors reported every ten\nminutes and the readings were averaged per day. Rainfall across the three stations rose
$ curl -s -w ' [%{http_code}]' -F file=@/tmp/big.pdf localhost:8099/convert {"detail":"File is larger than 10485760 bytes"} [413]
$ curl -s -w ' [%{http_code}]' -F file=@/home/user/MarkItDown/public/samples/pdf-scanned.pdf localhost:8099/convert {"filename":"pdf-scanned.pdf","characters":0,"markdown":""} [200]
- A Word file and a text PDF converted (200 with the Markdown).
- A
.gifand an.rtfwere refused with 415 before any conversion. - An 11 MB upload was refused with 413.
- An encrypted PDF gave 422 with only the exception name.
- A scanned PDF returned 200 with an empty
markdown: MarkItDown reports no error for it, so check the length if you need to tell users (OCR). - A 200-page PDF converted to 375,091 characters.
Choices
- No URLs and no paths are accepted, so a caller cannot make the service read a local file or fetch an address (security).
- Plugins are off and only the extras you install are available.
- Two worker threads: conversion is CPU-bound, so more threads do not help much (speed). The timeout stops waiting for the request but does not stop the thread; for hard limits, use a process or container limit, which we did not test.
Not tested
Docker, authentication, concurrency under load, the timeout path (504) and a deployment behind a proxy.