FormaTeX

\usepackage{python}

Python LaTeX to PDF API

Compile LaTeX to PDF from Python in a single HTTP request. Use the standard requests library or httpx for async — no SDK installation required.

Also available in:Python·Node.js·Go·PHP·Ruby·Rust·cURL|Full API reference

\section{Installation}

Installation

No SDK required. The FormaTeX API is a standard HTTP REST API. Install requests for synchronous use or httpx if you need async support.

terminal
pip install requests
# or with httpx for async
pip install httpx

\section{Quick Start}

Quick start

The example below compiles a minimal LaTeX document and saves the resulting PDF to disk. Replace your-api-key with a key from your dashboard.

quickstart.py
import requests

API_KEY = "your-api-key"  # get from formatex.io/dashboard/api-keys
API_URL = "https://api.formatex.io/v1"

latex_source = r"""
\documentclass{article}
\usepackage{amsmath}
\begin{document}
Hello from Python! $E = mc^2$
\end{document}
"""

response = requests.post(
    f"{API_URL}/compile/sync",
    headers={
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    },
    json={
        "source": latex_source,
        "engine": "pdflatex",
    },
)

response.raise_for_status()

with open("output.pdf", "wb") as f:
    f.write(response.content)

print("PDF saved to output.pdf")

\section{Authentication}

Authentication

All API requests must include an Authorization header with a Bearer token:

Authorization: Bearer your-api-key
  • Generate API keys from your dashboard after signing up.
  • Store keys in environment variables — never hardcode them in source files.
  • Use os.environ["FORMATEX_API_KEY"] to read the key at runtime.

\section{Engines}

Engine selection

Pass an engine field in your JSON body. Supported values: pdflatex, xelatex, lualatex, latexmk. See engine documentation for details.

engines.py
# Choose your engine
for engine in ["pdflatex", "xelatex", "lualatex", "latexmk"]:
    response = requests.post(
        f"{API_URL}/compile/sync",
        headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
        json={"source": latex_source, "engine": engine},
    )
    print(f"{engine}: {response.status_code}, {len(response.content)} bytes")

\section{Error Handling}

Error handling

The API returns HTTP status codes. A 422 means your LaTeX failed to compile — the JSON body contains an error field with the TeX log excerpt. 401 means an invalid or missing API key.

error_handling.py
import requests
from requests.exceptions import HTTPError

def compile_latex(source: str, engine: str = "pdflatex") -> bytes:
    """Compile LaTeX to PDF, raising on error with useful message."""
    try:
        response = requests.post(
            f"{API_URL}/compile/sync",
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json",
            },
            json={"source": source, "engine": engine},
            timeout=30,
        )
        response.raise_for_status()
        return response.content
    except HTTPError as e:
        if e.response.status_code == 422:
            error_data = e.response.json()
            raise ValueError(f"LaTeX compilation failed: {error_data.get('error')}") from e
        elif e.response.status_code == 401:
            raise PermissionError("Invalid API key. Check your FORMATEX_API_KEY.") from e
        raise

\section{Async}

Async with httpx

Use httpx.AsyncClient to compile documents concurrently inside async Python applications such as FastAPI or async scripts.

async_compile.py
import asyncio
import httpx

async def compile_latex_async(source: str) -> bytes:
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://api.formatex.io/v1/compile/sync",
            headers={
                "Authorization": f"Bearer {API_KEY}",
                "Content-Type": "application/json",
            },
            json={"source": source, "engine": "pdflatex"},
            timeout=30.0,
        )
        response.raise_for_status()
        return response.content

# Run it
pdf_bytes = asyncio.run(compile_latex_async(latex_source))

\section{Reference}

API reference

FieldTypeRequiredDescription
sourcestringYesFull LaTeX source code as a string
enginestringNoEngine to use. Default: "pdflatex". Options: pdflatex, xelatex, lualatex, latexmk

POST https://api.formatex.io/v1/compile/syncReturns raw PDF bytes on success (200), or JSON error on failure (422/401).

\end{python}

Start compiling LaTeX from Python

Get your API key, run the quickstart, and have PDF output in minutes.

One quick thing

We track anonymous usage — page views, feature usage, compilation events — to understand what works and what doesn't. No ads, no personal data, no third-party sharing.

Cookie policy