Migrating from Flask to FastAPI involves several key changes to your codebase. This guide will walk you through using Graph-sitter to automate this migration, handling imports, route decorators, static files, and template rendering.You can find the complete example code in our examples repository
from graph_sitter import Codebase# Parse the codebasecodebase = Codebase("./")# Update imports and initializationfor file in codebase.files: # Update Flask to FastAPI imports for imp in file.imports: if imp.name == "Flask": imp.set_name("FastAPI") elif imp.module == "flask": imp.set_module("fastapi") # Update app initialization for call in file.function_calls: if call.name == "Flask": call.set_name("FastAPI") # Remove __name__ argument (not needed in FastAPI) if len(call.args) > 0 and call.args[0].value == "__name__": call.args[0].remove()
This transforms code from:
Copy
Ask AI
from flask import Flaskapp = Flask(__name__)
to:
Copy
Ask AI
from fastapi import FastAPIapp = FastAPI()
FastAPI doesn’t require the __name__ argument that Flask uses for template
resolution. Graph-sitter automatically removes it during migration.
Next, we update Flask’s route decorators to FastAPI’s operation decorators:
Copy
Ask AI
for function in file.functions: for decorator in function.decorators: if "@app.route" in decorator.source: route = decorator.source.split('"')[1] method = "get" # Default to GET if "methods=" in decorator.source: methods = decorator.source.split("methods=")[1].split("]")[0] if "post" in methods.lower(): method = "post" elif "put" in methods.lower(): method = "put" elif "delete" in methods.lower(): method = "delete" decorator.edit(f'@app.{method}("{route}")')