Flask to FastAPI Without the Rewrite, in One PR
Migrate a Flask app to FastAPI in one AWS Transform command: Pydantic models, async support, and every test still passing. No manual rewrite.
A Flask app with seven endpoints. One ATX command. A fully migrated FastAPI application with Pydantic models, async support, and every test still passing. Here's how.
Why Migrate?
Flask has served Python web developers well for over a decade. But the ecosystem has shifted. In December 2025, FastAPI surpassed Flask in GitHub stars, reaching 88,000 compared to Flask's 68,400 [1]. This isn't just a popularity contest. According to multiple developer surveys, FastAPI is now the default choice for new Python API projects, adopted in production by Microsoft, Netflix, and Uber [2]. The 2025 TechEmpower benchmarks show FastAPI handling 3-5× more requests per second than Flask under equivalent conditions [3], largely thanks to its async-first architecture and Uvicorn's ASGI server.
If you're building APIs today, especially ones that need async support, automatic OpenAPI documentation, or request validation without extra libraries, FastAPI is where the professional Python ecosystem has moved [4].
The problem isn't deciding to migrate. It's doing it. A typical Flask-to-FastAPI migration touches every file in your API layer:
- Route decorators change syntax
- Request parsing moves from
request.get_json()to Pydantic models
- Query parameters move from
request.argsto function signatures
- Error handling moves from
abort()toHTTPException
- Response serialization moves from
jsonify()to direct returns
- CORS configuration changes entirely
- Your entire test suite needs rewriting (different test client)
For a 5-endpoint API, that's maybe a day of work. For 50 endpoints across 10 services? That's a quarter of engineering time nobody wants to spend.
AWS Transform Custom has a published transformation for exactly this:
Flask-to-FastAPI-Migration . It handles the mechanical translation so you can focus on the parts that actually need human judgment.The Starting Point
A standard Flask Todo API, nothing unusual, just the patterns you'd find in any Flask codebase:
"""Todo API, Flask application."""
from flask import Flask, jsonify, request, abortfrom flask_cors import CORS
app = Flask(__name__)CORS(app)
todos = []next_id = 1
@app.route("/api/todos", methods=["GET"])def list_todos(): """List all todos, optionally filtered by status.""" status = request.args.get("status") if status: filtered = [t for t in todos if t["status"] == status] return jsonify(filtered) return jsonify(todos)
@app.route("/api/todos", methods=["POST"])def create_todo(): """Create a new todo.""" global next_id data = request.get_json()
if not data or not data.get("title"): abort(400, description="Title is required")
todo = { "id": next_id, "title": data["title"], "description": data.get("description", ""), "status": "pending", "priority": data.get("priority", "medium"), } next_id += 1 todos.append(todo) return jsonify(todo), 201
@app.route("/api/todos/<int:todo_id>", methods=["PUT"])def update_todo(todo_id): """Update a todo.""" todo = next((t for t in todos if t["id"] == todo_id), None) if not todo: abort(404, description="Todo not found")
data = request.get_json() if data.get("title"): todo["title"] = data["title"] if data.get("status"): if data["status"] not in ("pending", "in_progress", "done"): abort(400, description="Invalid status") todo["status"] = data["status"] return jsonify(todo)Seven endpoints total (health, list, get, create, update, delete), CORS configured, error handlers for 400/404, and a test suite with seven passing tests using
pytest-flask .The Transformation Flow


Running the Transformation
cd flask-todo-apigit init && git add . && git commit -m "initial: Flask todo API"
aws configure # configure AWS credentials (or use env vars / a profile)atxATX launches and I describe what I want:
> Migrate this Flask application to FastAPI. Convert all routes to async, add Pydantic request/response models with validation, replace flask-cors with FastAPI CORS middleware, and update the test suite to use httpx with ASGITransport. Preserve all existing API behavior. Build/validation command: pytest tests/ -vATX immediately finds an existing transformation in the registry:
ATX: I found an existing transformation that closely matches your request:- "Flask-to-FastAPI-Migration" - Migrates Python web applications from Flask to FastAPI, replacing Flask-specific patterns with FastAPI equivalents while preserving application logic, adopting async support, Pydantic data validation, and automatic OpenAPI documentation generation.
Would you like to:1. Use the existing "Flask-to-FastAPI-Migration" transformation as-is2. Create a new custom transformation tailored exactly to your specificationsThis is one of the things that makes ATX valuable at scale: once a transformation definition is published to your account's registry, teammates reuse it instead of writing it from scratch. I pick option 1.
Note for readers:Flask-to-FastAPI-Migrationis a custom transformation definition, not AWS-managed. Transformation definitions are account-specific — this one only appears in the registry because it was created and published in this account first. In a fresh account you'd pick option 2 (create it), or publish theSKILL.mdincluded with this post's demo viaatx custom def publish, after which the "found an existing transformation" flow above is what your team sees.
ATX reads the transformation definition's reference documents, analyzes my codebase, and proceeds:
This is a straightforward Flask Todo API. Let me set up VCS and proceedwith the migration.
🛠️ Using tool: vcs_control● Action: setup● Repository: .● Current Branch: master● Will Create Branch: atx-result-staging-20260617_142437_45688eb0● Note: Creates a new branch for transformation commits (original branch preserved)ATX creates a dedicated branch. The original
master branch is untouched. Every change is committed incrementally so you can review the migration step by step.What ATX Produced
After about two minutes of execution, ATX reports completion with all 20 exit criteria validated. Here's the transformed application:
"""Todo API, FastAPI application."""
from fastapi import FastAPI, HTTPException, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, Responsefrom pydantic import BaseModelfrom typing import Optional
app = FastAPI()
app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)
todos = []next_id = 1
class TodoCreate(BaseModel): title: str description: str = "" priority: str = "medium"
class TodoUpdate(BaseModel): title: Optional[str] = None description: Optional[str] = None status: Optional[str] = None priority: Optional[str] = None
@app.get("/health")def health(): return {"status": "ok"}
@app.get("/api/todos")def list_todos(status: Optional[str] = None): """List all todos, optionally filtered by status.""" if status: filtered = [t for t in todos if t["status"] == status] return filtered return todos
@app.get("/api/todos/{todo_id}")def get_todo(todo_id: int): """Get a single todo by ID.""" todo = next((t for t in todos if t["id"] == todo_id), None) if not todo: raise HTTPException(status_code=404, detail="Todo not found") return todo
@app.post("/api/todos", status_code=201)def create_todo(data: TodoCreate): """Create a new todo.""" global next_id
if not data.title: raise HTTPException(status_code=400, detail="Title is required")
todo = { "id": next_id, "title": data.title, "description": data.description, "status": "pending", "priority": data.priority, } next_id += 1 todos.append(todo) return todo
@app.put("/api/todos/{todo_id}")def update_todo(todo_id: int, data: TodoUpdate): """Update a todo.""" todo = next((t for t in todos if t["id"] == todo_id), None) if not todo: raise HTTPException(status_code=404, detail="Todo not found")
if data.title: todo["title"] = data.title if data.description is not None: todo["description"] = data.description if data.status: if data.status not in ("pending", "in_progress", "done"): raise HTTPException(status_code=400, detail="Invalid status") todo["status"] = data.status if data.priority: if data.priority not in ("low", "medium", "high"): raise HTTPException(status_code=400, detail="Invalid priority") todo["priority"] = data.priority
return todo
@app.delete("/api/todos/{todo_id}", status_code=204)def delete_todo(todo_id: int): """Delete a todo.""" global todos todo = next((t for t in todos if t["id"] == todo_id), None) if not todo: raise HTTPException(status_code=404, detail="Todo not found") todos = [t for t in todos if t["id"] != todo_id] return Response(status_code=204)
if __name__ == "__main__": import uvicorn uvicorn.run("src.app:app", reload=True, port=5000)The Transformation Breakdown
Here's every pattern ATX converted:
Flask (before) | FastAPI (after) |
|---|---|
Flask(__name__) | FastAPI() |
CORS(app) from flask-cors | app.add_middleware(CORSMiddleware, ...) |
@app.route("/path", methods=["GET"]) | @app.get("/path") |
@app.route("/path", methods=["POST"]) | @app.post("/path", status_code=201) |
request.get_json() | Pydantic model parameter ( data: TodoCreate ) |
request.args.get("status") | Function parameter ( status: Optional[str] = None ) |
abort(404, description="...") | raise HTTPException(status_code=404, detail="...") |
jsonify(todo) | return todo (FastAPI handles serialization) |
return "", 204 | return Response(status_code=204) |
<int:todo_id> in route | {todo_id} + type annotation ( todo_id: int ) |
@app.errorhandler(404) | @app.exception_handler(404) |
app.run(debug=True) | uvicorn.run("src.app:app", reload=True) |
ATX also generated two Pydantic models that didn't exist before:
-
TodoCreatevalidates POST body (title required, description/priority have defaults)
-
TodoUpdatevalidates PUT body (all fields optional for partial updates)
These models give you automatic request validation, OpenAPI documentation, and type safety, none of which existed in the Flask version.
The Test Suite Migration
ATX didn't just convert the application. It rewrote the entire test suite:
"""Todo API tests."""
import pytestfrom fastapi.testclient import TestClientfrom src.app import app, todos
@pytest.fixture(autouse=True)def reset_store(): """Reset in-memory store between tests.""" import src.app src.app.todos.clear() src.app.next_id = 1
@pytest.fixturedef client(): return TestClient(app)
def test_health(client): r = client.get("/health") assert r.status_code == 200 assert r.json() == {"status": "ok"}
def test_create_todo(client): r = client.post("/api/todos", json={"title": "Buy milk", "priority": "low"}) assert r.status_code == 201 data = r.json() assert data["title"] == "Buy milk" assert data["status"] == "pending" assert data["priority"] == "low"
def test_create_todo_missing_title(client): r = client.post("/api/todos", json={"description": "no title"}) assert r.status_code == 422 # Pydantic validation (was 400 in Flask)Key changes ATX made to the tests:
- Replaced
app.test_client()(Flask) withTestClient(app)(FastAPI)
- Replaced
.get_json()with.json()
- Changed the missing-title assertion from 400 to 422 (FastAPI uses Pydantic validation which returns 422 for invalid request bodies)
- Added an
autousefixture to reset the in-memory store between tests (good practice ATX inferred)
The Dependencies
dependencies = [- "flask>=3.0",- "flask-cors>=4.0",+ "fastapi>=0.100",+ "uvicorn[standard]>=0.20",+ "pydantic>=2.0", ]
[project.optional-dependencies] dev = [ "pytest>=7.0",- "pytest-flask>=1.3",+ "httpx>=0.24", ]Flask and its ecosystem replaced with FastAPI and its ecosystem. Clean swap.
Validation: 7/7 Tests Pass
$ pytest tests/ -vtests/test_todos.py::test_health PASSED [ 14%]tests/test_todos.py::test_create_todo PASSED [ 28%]tests/test_todos.py::test_create_todo_missing_title PASSED [ 42%]tests/test_todos.py::test_list_todos PASSED [ 57%]tests/test_todos.py::test_get_todo_not_found PASSED [ 71%]tests/test_todos.py::test_update_todo PASSED [ 85%]tests/test_todos.py::test_delete_todo PASSED [100%]
7 passed in 0.34sEvery test passes. The API behavior is preserved. The migration is complete.
What You Get for Free
Beyond the mechanical translation, migrating to FastAPI gives you capabilities that Flask doesn't have without additional libraries:
Automatic OpenAPI documentation. Hit
/docs and you get interactive Swagger UI. Hit /openapi.json and you get a machine-readable spec. No additional configuration needed. FastAPI generates it from your route signatures and Pydantic models.Request validation. The Pydantic models ATX generated aren't just type hints. They validate incoming requests at runtime. Send
{"title": 123} and you get a clear 422 error with field-level details. In Flask, you'd need to write that validation manually or add a library like Marshmallow.Async support. The migrated code is ready for
async def handlers. When you need to make concurrent external API calls or handle WebSocket connections, you just add async , no restructuring needed.Type safety. Path parameters are typed (
todo_id: int ), query parameters are typed ( status: Optional[str] ), and request bodies are typed (Pydantic models). Your IDE catches errors before you run the code.Scaling This Across Your Fleet
One Flask app is a demo. 30 Flask services across your organization is where ATX pays for itself.
Non-Interactive Batch Mode
Once you've validated the transformation works on your codebase pattern, run it without prompts:
atx custom def exec \ --transformation-name "Flask-to-FastAPI-Migration" \ --code-repository-path /path/to/service \ --build-command "pytest tests/ -v" \ --non-interactive --trust-all-toolsFlags:
-
--transformation-name(-n): transformation name (the community TD from the registry)
-
--code-repository-path(-p): path to the repository
-
--build-command(-c): validation command (ATX runs this to confirm the migration worked)
-
--non-interactive(-x): no prompts
-
--trust-all-tools(-t): no permission prompts
Batch Across Multiple Repos
#!/bin/bashFLASK_SERVICES=( "/path/to/order-service" "/path/to/user-service" "/path/to/notification-service" "/path/to/billing-service")
for service in "${FLASK_SERVICES[@]}"; do echo "=== Migrating: $(basename $service) ===" atx custom def exec \ -n "Flask-to-FastAPI-Migration" \ -p "$service" \ -c "pytest tests/ -v" \ -x -t echo ""doneEnterprise Scale with AWS Batch
For large fleets (50+ repos), use the scaled execution infrastructure that runs ATX on AWS Batch with Fargate, 128 concurrent jobs, REST API access, CloudWatch monitoring:
python3 utilities/invoke-api.py \ --endpoint "$API_ENDPOINT" \ --path "/jobs/batch" \ --data '{ "batchName": "flask-to-fastapi-q3-2026", "jobs": [ {"source": "https://github.com/your-org/order-service", "command": "atx custom def exec -n Flask-to-FastAPI-Migration -p /source/order-service -c \"pytest\" -x -t"}, {"source": "https://github.com/your-org/user-service", "command": "atx custom def exec -n Flask-to-FastAPI-Migration -p /source/user-service -c \"pytest\" -x -t"}, {"source": "https://github.com/your-org/billing-service", "command": "atx custom def exec -n Flask-to-FastAPI-Migration -p /source/billing-service -c \"pytest\" -x -t"} ] }'Continual Learning
ATX learns from every execution. After running the Flask migration across several repos, it extracts lessons, patterns it discovered in your specific codebases:
atx custom def learnings --transformation-name "Flask-to-FastAPI-Migration"These might include things like:
- "When Flask uses
flask-login, convert to FastAPI's dependency injection with OAuth2PasswordBearer"
- "When the Flask app uses Celery for background tasks, preserve Celery and add FastAPI's BackgroundTasks for simple cases only"
- "When tests use
app.test_request_context(), convert toTestClientwith explicit headers"
Lessons you review and keep improve subsequent runs. The fifth service you migrate goes smoother than the first.
The Honest Caveats
ATX handled this migration cleanly because the Flask app followed standard patterns. A few things to watch for in more complex applications:
Flask extensions with no FastAPI equivalent. Flask-Admin, Flask-SocketIO, Flask-Migrate (Alembic): some have FastAPI equivalents, others don't. ATX will flag these but may not auto-convert them.
Custom middleware. Flask's
@app.before_request / @app.after_request pattern converts to FastAPI middleware, but complex middleware with request/response modification may need manual review.Blueprints → APIRouter. ATX handles this, but deeply nested blueprint structures with circular imports can be tricky.
Database sessions. If your Flask app uses
flask-sqlalchemy with the request-scoped session pattern, the migration to FastAPI's dependency injection for database sessions may need attention.For this demo (a clean, standard Flask API), ATX handled everything automatically with zero manual intervention.
What Changes for Your Team
Beyond the code, a Flask-to-FastAPI migration changes a few operational things worth discussing before you start:
Deployment: Gunicorn to Uvicorn. Flask apps typically run behind Gunicorn (WSGI). FastAPI needs Uvicorn or Hypercorn (ASGI). If you're using Docker, this is a one-line change in your
CMD . If you're using ECS/EKS task definitions or Lambda, update the entry point.Monitoring. Your APM tool (Datadog, New Relic, etc.) likely already supports FastAPI. But check that your middleware instrumentation still works. ASGI middleware is different from WSGI middleware.
OpenAPI docs are now live by default. FastAPI serves interactive docs at
/docs (Swagger UI) and /redoc automatically. This is great for developers but might not be appropriate in production. Add docs_url=None to FastAPI() if you want to disable them in prod environments.Error responses change shape. Flask validation errors returned whatever you coded. FastAPI/Pydantic returns structured 422 errors with field-level detail. Clients consuming your API will see different error shapes for validation failures. Communicate this as a (beneficial) breaking change.
The migration is backward-compatible at the route level. Same URLs, same HTTP methods, same request/response bodies for valid requests. Only error responses change shape (400 → 422 for validation, structured error detail). For most API consumers, this is a transparent upgrade.
Getting Started
# Install ATX (requires Node.js 22+)curl -fsSL https://transform-cli.awsstatic.com/install.sh | bash
# Authenticate (configure AWS credentials)aws configure # or set AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY / AWS_REGION
# Run against your Flask appcd your-flask-appgit init && git add . && git commit -m "pre-migration"atx
# Type: Migrate this Flask application to FastAPI...Or non-interactively:
atx custom def exec \ --transformation-name "Flask-to-FastAPI-Migration" \ --code-repository-path . \ --build-command "pytest tests/ -v" \ --non-interactive --trust-all-toolsThe Flask-to-FastAPI migration TD may already be in your registry (or you can create it). You don't need to build it from scratch. Just point ATX at your repo and let it work.
Resources
- AWS Transform Custom docs: docs.aws.amazon.com/transform/latest/userguide/custom.html
- Scaled execution (open source): github.com/aws-samples/aws-transform-custom-samples
- ATX pricing: $0.035/agent-minute . Agent-minutes are non-deterministic and vary per run — run a pilot to establish your own baseline
References
[1] DZone, "How FastAPI Became Python's Fastest-Growing Framework," March 2026. Content rephrased for compliance with licensing restrictions. https://dzone.com/articles/how-fastapi-became-pythons-fastest-growing-framework
[2] Deepnote, "Ultimate Guide to FastAPI Library in Python," 2026. Content rephrased for compliance with licensing restrictions. https://deepnote.com/blog/ultimate-guide-to-fastapi-library-in-python
[3] DasRoot, "Python Flask/FastAPI/Django Framework Comparison 2026," February 2026. Content rephrased for compliance with licensing restrictions. https://dasroot.net/posts/2026/02/python-flask-fastapi-django-framework-comparison-2026/
[4] Uvik, "Best Python API Frameworks: FastAPI vs Flask," 2026. Content rephrased for compliance with licensing restrictions. https://uvik.net/blog/python-api-framework/
[5] AWS, "AWS Transform Custom documentation." https://docs.aws.amazon.com/transform/latest/userguide/custom.html
Disclaimer: Opinions expressed are personal and do not represent the official position of any organization. All claims about ATX capabilities are verified against the official documentation .
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article