Deploying scripts as an API in Azure
Deploying local python scripts and converting them as an API.
Published Updated
In this article
- An async endpoint reads a 25 MB upload and then runs CPU-heavy PDF parsing. Why does async not protect request latency?
- Explain the version and execution boundaries before applying the examples
Background & source details
Level: beginner
Bring with you
Sources checked: . A source check does not change the publication or update date.
Editorial review: · What review means
In this article · 17 sections
Deploying a Python Script as an API on Azure
Goal: Turn a local PDF extractor into a bounded HTTP service, then reason through packaging, hosting and release checks. The code is a teaching fragment; the Azure deployment and hostile-PDF isolation steps are a deployment plan, not an executed result.
📋 What This Blog Covers
A local extractor assumes one trusted file and one person waiting for the result. An API has to accept uploads from other callers, reject unsuitable inputs, and keep working when requests overlap. Each step below adds one part of that service boundary; the container packages the extractor, but does not supply authentication or safe request handling on its own.
Figure text equivalent — labels and relationships
- Node “📄 Local Python Script” (square).
- Node “🌐 REST API (FastAPI/Flask)” (square).
- Node “🐳 Docker Container” (square).
- Node “☁️ Azure Deployment” (square).
- Node “🔒 Auth + Monitoring” (square).
- “📄 Local Python Script” leads to “🌐 REST API (FastAPI/Flask)”. Line: normal; ends: arrow point.
- “🌐 REST API (FastAPI/Flask)” leads to “🐳 Docker Container”. Line: normal; ends: arrow point.
- “🐳 Docker Container” leads to “☁️ Azure Deployment”. Line: normal; ends: arrow point.
- “☁️ Azure Deployment” leads to “🔒 Auth + Monitoring”. Line: normal; ends: arrow point.
- Sample local script to extract content from PDF
- Available options to deploy the script as an API
- Designing the deployment architecture
- Implementation and testing
Script resources: GitHub Repo
🔧 Background & Prerequisites
1. PDF Content Extraction — The Script
| Library | Strengths | Best For |
|---|---|---|
| PyMuPDF (fitz) | Supports text/layout extraction; benchmark your documents | General text extraction |
| pdfplumber | Excellent table extraction | Tabular data |
| PyPDF2 | Lightweight, basic extraction | Simple PDFs |
| Tesseract OCR | Open-source OCR for scanned PDFs | Image-based PDFs |
| Azure Doc Intelligence | Cloud-based, layout analysis | Enterprise extraction |
Key extraction targets:
- 📝 Text — Full-text extraction from each page
- 📊 Tables — Structured table data
- 🏷️ Metadata — Title, author, creation date, page count (
PdfReader(file).metadata) - 🔍 OCR fallback — Detect if PDF has extractable text; if not, route to OCR
2. API Design
Follow one upload through the sequence below. Validation belongs before extraction because PDF parsing is the expensive, failure-prone part; the client should receive a structured error rather than a parser traceback. The request waits for extraction to finish, so large or OCR-heavy documents may need a queued job instead of this synchronous request/response design.
Figure text equivalent — labels and relationships
- Participant “Client”.
- Participant “FastAPI Server”.
- Participant “PDF Extractor”.
- 1. solid: “Client” to “FastAPI Server” — POST /api/extract (multipart/form-data).
- 2. solid: “FastAPI Server” to “FastAPI Server” — Validate file type & size.
- 3. solid: “FastAPI Server” to “PDF Extractor” — Extract text + metadata.
- 4. dotted: “PDF Extractor” to “FastAPI Server” — Structured result.
- 5. dotted: “FastAPI Server” to “Client” — 200 JSON response {text, metadata, page_count, processing_time_ms}.
| Aspect | Design Decision |
|---|---|
| Endpoint | POST /api/extract — upload PDF, get extracted data |
| Input | multipart/form-data file upload (direct upload; URL ingestion requires a separate SSRF-resistant design) |
| Output | JSON: {text, metadata, page_count, tables, processing_time_ms} |
| Validation | File type check, size limits, malware considerations |
| Status Codes | 200 success, 400 bad request, 413 too large, 500 error |
| Docs | OpenAPI/Swagger auto-generated (built into FastAPI) |
| Auth | API key in header or Azure Entra ID token |
3. Framework Choice — Flask vs FastAPI
Framework choice begins with the workload, not a speed adjective. This endpoint accepts an upload, parses an untrusted document and returns structured data. Its parser cost and concurrency limits can dominate either framework.
| Question | Flask | FastAPI |
|---|---|---|
| Request execution | WSGI by default; async views are supported with the async extra, but each request still occupies a worker | ASGI; supports both async def and regular def handlers |
| Schema and API documentation | Select validation/OpenAPI extensions or implement the contracts explicitly | Type-driven validation and generated OpenAPI documentation are built into the usual workflow |
| Existing application | Often sensible when middleware, authentication and operational practice already use Flask | Often sensible for a new typed API or an existing ASGI application |
| Synchronous parser | Must bound worker use and isolate hostile/expensive parsing | A regular def path operation runs in an external threadpool; that is not a parser sandbox or unlimited capacity |
Flask's documentation explicitly warns that async is not inherently faster and does not make CPU-bound work faster. FastAPI's execution model explains why an ordinary def handler is offloaded instead of called directly on the event-loop thread. Calling a blocking parser inside an async def function does not offload that call automatically.
For this example, choose FastAPI for the request contract and documentation, not a promised throughput advantage. If a hypothetical parse takes 0.2 CPU-seconds, one fully occupied CPU core has a rough compute ceiling of five such parses per second before any other work. Changing the HTTP framework does not remove those CPU-seconds. Native parser behavior, document complexity and isolation overhead must be measured separately. For long or hostile inputs, accept a bounded job, return a job identifier, and parse in an isolated worker; choose either framework for the admission/status API.
Decision exercise. An existing Flask service already has tested authorization, while a new parser consumes seconds of CPU per request. Would migrating it to FastAPI eliminate the need for a job queue? Answer: no. Keeping Flask may reduce migration risk; either framework still needs bounded admission, execution isolation, ownership checks and a measured latency budget. An ASGI migration is a separate application decision, not a cure for parser cost.
4. Containerization with Docker
# Example multi-stage Dockerfile
FROM python:3.12-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
FROM python:3.12-slim
WORKDIR /app
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages
COPY . .
RUN useradd --uid 10001 --create-home app
USER app
EXPOSE 8000
HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)"
CMD ["python", "-m", "uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]💡 Tips: Use multi-stage builds to reduce image size. Install system deps like
poppler-utilsfor pdftotext. Pass secrets via environment variables — never hardcode.
Check the final stage, not just the builder. This fragment invokes Uvicorn as a Python module, so its missing copied console-script entrypoint is not required; its probe uses the Python standard library already in the base image. The requirements must still include the server, multipart handling and parser packages, and their native runtime dependencies must exist in the final stage. Both stages must use compatible interpreter/OS/architecture versions. Multi-stage copying does not by itself prove a smaller or runnable image; build and probe the actual locked artifact before deployment.
5. Azure Deployment Options
Once the image is in ACR, the branches below are alternative places to run it—not services that every request must pass through. Choose based on the traffic pattern and operational burden: a sporadically used PDF API makes scale-to-zero attractive, but callers still experience cold starts and document-processing time.
Figure text equivalent — labels and relationships
- Node “🐍 Python Script” (square).
- Node “🐳 Docker Image” (square).
- Node “📦 Azure Container Registry” (square).
- Node “⭐ Container Apps (Recommended)” (square).
- Node “🌐 App Service” (square).
- Node “⚡ Azure Functions” (square).
- Node “📦 Container Instances” (square).
- Node “☸️ AKS” (square).
- “🐍 Python Script” leads to “🐳 Docker Image”. Line: normal; ends: arrow point.
- “🐳 Docker Image” leads to “📦 Azure Container Registry”. Line: normal; ends: arrow point.
- “📦 Azure Container Registry” leads to “⭐ Container Apps (Recommended)”. Line: normal; ends: arrow point.
- “📦 Azure Container Registry” leads to “🌐 App Service”. Line: normal; ends: arrow point.
- “📦 Azure Container Registry” leads to “⚡ Azure Functions”. Line: normal; ends: arrow point.
- “📦 Azure Container Registry” leads to “📦 Container Instances”. Line: normal; ends: arrow point.
- “📦 Azure Container Registry” leads to “☸️ AKS”. Line: normal; ends: arrow point.
| Hosting direction | What to establish before choosing it |
|---|---|
| Container Apps | A bounded replica range and suitable scaling trigger; ingress, registry identity, resource limits and cold-start tolerance |
| App Service | A suitable container-capable plan, startup/probe configuration and a capacity/cost model for the selected SKU |
| Azure Functions | A Functions application/runtime and supported container hosting mode, not an unchanged arbitrary Uvicorn image |
| Container Instances | Container-group lifecycle, restart and networking requirements; do not assume an application autoscaler |
| AKS | Whether cluster operation is justified by workloads, policy or an existing platform rather than this one small API |
For this walkthrough, Container Apps is the chosen example, not a universal cheapest host. Its scaling documentation describes revision replica limits and HTTP/TCP/custom rules. A minimum of zero enables a zero-replica state under an appropriate rule; it does not guarantee zero total project cost or zero cold-start latency. A positive minimum keeps capacity available at a cost. Price comparisons require region, currency, workload, plan, storage and egress assumptions; the old fixed monthly-price shorthand is deliberately not used.
The Functions branch is an adaptation, not a drop-in deployment target for the Dockerfile above. Containerized Functions use a supported Functions base image/runtime and programming model. A plain python -m uvicorn container is a web API container, not automatically a Functions app.
6. CI/CD Pipeline
The release path below moves an image, not a user PDF. Before promoting that image from staging, run extraction against representative documents and verify the error responses; a successful build or registry push says nothing about whether the service can parse an upload.
Figure text equivalent — labels and relationships
- Node “📤 Git Push” (square).
- Node “🏗️ GitHub Actions” (square).
- Node “🐳 Build Docker Image” (square).
- Node “📦 Push to ACR” (square).
- Node “🚀 Deploy to Container Apps” (square).
- “📤 Git Push” leads to “🏗️ GitHub Actions”. Line: normal; ends: arrow point.
- “🏗️ GitHub Actions” leads to “🐳 Build Docker Image”. Line: normal; ends: arrow point.
- “🐳 Build Docker Image” leads to “📦 Push to ACR”. Line: normal; ends: arrow point.
- “📦 Push to ACR” leads to “🚀 Deploy to Container Apps”. Line: normal; ends: arrow point.
- Use GitHub Actions for automated build → push → deploy
- Store Azure credentials and API keys in GitHub Secrets
- Maintain separate staging and production environments
✅ TODO — Remaining Work
Treat this as an implementation checklist for your own environment. The bounded text/metadata endpoint and Dockerfile are supplied below; tables, OCR, authentication, image builds and Azure operations are still separate work, not claimed completed features.
| # | Task | Priority |
|---|---|---|
| 1 | Write PDF extraction script (PyMuPDF: metadata + text + tables) | 🔴 High |
| 2 | Wrap in FastAPI with endpoints, validation, error handling | 🔴 High |
| 3 | Add OpenAPI/Swagger documentation | 🔴 High |
| 4 | Write Dockerfile and test locally | 🔴 High |
| 5 | Push image to Azure Container Registry | 🟡 Medium |
| 6 | Deploy to Azure Container Apps | 🟡 Medium |
| 7 | Set up GitHub Actions CI/CD pipeline | 🟡 Medium |
| 8 | Add authentication (API key or Azure Entra ID) | 🟡 Medium |
| 9 | Load test with sample PDFs and document performance | 🟢 Low |
| 10 | Create full architecture diagram with all components | 🟢 Low |
🧩 Reference Implementation — FastAPI Service
This bounded synchronous endpoint runs in FastAPI's worker threadpool rather than executing a CPU parser directly on the async event loop. The UploadFile multipart body has already been received/spooled by the framework: this application read limit is not a total ingress-memory or multipart denial-of-service defense. Enforce ingress/body/time/concurrency limits before parsing and isolate hostile PDF parsing in a constrained job worker for production.
from fastapi import FastAPI, UploadFile, File, HTTPException
import fitz
import time
MAX_BYTES = 25 * 1024 * 1024
MAX_PAGES = 100
MAX_TEXT = 1_000_000
app = FastAPI()
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/api/extract")
def extract(file: UploadFile = File(...)):
started = time.perf_counter()
try:
data = file.file.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise HTTPException(413, "File too large")
if not data.startswith(b"%PDF-"):
raise HTTPException(400, "Expected a PDF signature")
try:
with fitz.open(stream=data, filetype="pdf") as doc:
if doc.needs_pass or doc.page_count > MAX_PAGES:
raise HTTPException(400, "Encrypted or over-page-limit PDF")
pieces = []
total = 0
for page in doc:
text = page.get_text()
total += len(text)
if total > MAX_TEXT:
raise HTTPException(413, "Extracted text too large")
pieces.append(text)
return {"text": "\n\n".join(pieces), "page_count": doc.page_count,
"metadata": {k: (doc.metadata or {}).get(k) for k in ("title", "author")},
"processing_time_ms": int(1000 * (time.perf_counter() - started))}
except HTTPException:
raise
except Exception:
raise HTTPException(400, "PDF could not be parsed") from None
finally:
file.file.close()A signature/content-type check is not malware analysis. This fragment omits authentication, tables and OCR explicitly; add those behind the same authorization/job boundary. CPU/memory limits must constrain the parser itself, because one page can be expensive before a text-size check runs. Test empty, malformed, encrypted, oversized, too-many-pages and no-text/scanned inputs; return a stable error without parser traceback or document contents.
Deploying to Azure Container Apps
Separate image construction, identity grants, deployment configuration and traffic promotion. Build in an authorized environment from a reviewed lockfile/base digest, scan the final runtime image and record its digest. Create or select a workload identity that can pull from the chosen registry under its actual permission mode; assign that grant before expecting a revision to start. A user-assigned identity can resolve the bootstrap dependency, while a system-assigned path requires the corresponding staged setup. Do not copy the old one-shot create command as though registry access were automatic.
Configure the intended ingress exposure and target port 8000, startup/readiness/liveness probes, resource limits and a bounded replica range. A Container Apps revision is an immutable deployment snapshot, not a backup of external data. In multiple-revision mode, send a small authorized test slice to the new revision and verify the exact image digest, health, authentication, error semantics and latency before changing traffic weights. Scale-to-zero trades idle compute for cold-start latency; select a minimum replica count from actual requirements rather than promising a fixed cold-start time.
Keep secrets out of the image and deployment logs. Readiness should report boolean dependency health without returning document contents or secret lengths. The endpoint must still authorize the caller and job/document owner even if ingress is private. Rollback changes traffic to a compatible prior revision; it does not reverse uploaded files, extracted records or schema changes. None of these service operations was executed in this review.
Testing
Use a layered test matrix rather than “100 concurrent uploads succeeded” as a production threshold:
| Input or event | Expected behavior | What it establishes |
|---|---|---|
| Empty or non-PDF bytes | Stable 400, no parser traceback | Error boundary |
| More than MAX_BYTES | Read at most MAX_BYTES+1 upload bytes, then return 413 | Application read bound, not total memory or ingress bound |
| Password-protected PDF | Documented rejection or explicit authorized password workflow | No accidental partial result |
| More than MAX_PAGES | Rejection before page extraction | Page-count contract |
| A single expensive page | Worker deadline/resource limit and safe failure | Requires isolated parser/runtime test |
| No extractable text | Empty text plus an explicit OCR-required outcome in a richer API | Not silently treated as successful OCR |
| Wrong tenant/job owner | Denied before result download | Authorization |
| Worker crash or client retry | One durable job/effect; partial artifacts not published | Idempotency/recovery |
Mocking the parser tests endpoint decisions; it does not test PDF safety or PyMuPDF behavior. The scoped review syntax-checks the exact Python block but imports no third-party SDK and does not invoke the parser. Real parser fixtures and concurrent-load measurements remain application-environment checks with known resource limits.
Corrected contracts and failure analysis
An upload endpoint is a trust boundary: limit ingress bytes, multipart parsing, decoded pages, extracted text, processing time and concurrency independently. UploadFile spools to disk after its framework threshold, but reading the whole file still allocates memory. The corrected example reads at most MAX_BYTES+1, closes both file and document on failure, returns stable errors and avoids CPU parsing on the async event loop. A signature check does not make a PDF safe.
The Dockerfile now invokes python -m uvicorn, so copying site-packages does not leave a missing console-script entrypoint, and the probe uses the Python standard library rather than an absent curl executable. Production parsing belongs in a bounded isolated worker with authentication, job ownership, cancellation and retention. Tables and OCR are separate extraction objectives; the simple text endpoint does not falsely implement them.
Container Apps revisions and App Service slots provide different hosting contracts. Promote the tested image digest and verify runtime identity, ingress, probes and startup dependencies before claiming deployment success.
Boundary exercise with solution
An async endpoint reads a 25 MB upload and then runs CPU-heavy PDF parsing. Why does async not protect request latency?
Solution and reasoning
The synchronous parser blocks that event-loop thread. Offload bounded work or use a worker queue/process with resource limits. Reading MAX_BYTES+1 caps this application buffer, not multipart ingress or decompression cost. Test malformed, oversized, encrypted and slow documents, not only a small happy-path PDF.
Review and execution boundary
Python 3.12, FastAPI UploadFile and PyMuPDF 1.x conceptual service; no package installation, PDF parser or cloud execution.
Reviewed on 7 October 2026 against the official source snapshots linked below. The review is bounded editorial correction, not certification of every dependency, security property or cloud deployment. Historical setup commands and optional exercises were not executed. No cloud resources, third-party packages or external side effects were created. Old screenshots and unavailable private assets remain in the private recovery archive, not prerequisites for this lesson.
Source-backed review notes
-
Request Files - FastAPI — accessed 2026-10-07. Exact supporting passage: “It exposes an actual Python SpooledTemporaryFile object that you can pass directly to other libraries that expect a file-like object.”
-
Multi-stage builds | Docker Docs — accessed 2026-10-07. Exact supporting passage: “With multi-stage builds, you use multiple FROM statements in your Dockerfile. Each FROM instruction can use a different base, and each of them begins a new stage of the build. You can selectively copy artifacts from one stage to another, leaving behind everything you don't want in the final image.”
-
Update and deploy changes in Azure Container Apps | Microsoft Learn — accessed 2026-10-07. Exact supporting passage: “Immutable: Once established, a revision remains unchangeable.”
-
Flask async execution, FastAPI concurrency, Container Apps scaling and Functions containers — checked 7 October 2026 for the framework and hosting decisions above, not benchmark or deployment reproduction.
Pause / Recall / Apply
Can you explain it without the page?
Close the example. Reconstruct the core idea, then change one assumption. Mark complete when you’re ready; you can always undo it.
Stored in this browser only. No account, no sync. Clearing browser data removes your record.