FastAPI vs Flask Cheatsheet
1. Basic Route
FastAPI:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def read_root():
return {'message': 'Hello, FastAPI!'}
Flask:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def read_root():
return 'Hello, Flask!'
2. Path Parameters
FastAPI:
@app.get('/items/{item_id}')
def read_item(item_id: int):
return {'item_id': item_id}
Flask:
@app.route('/items/<int:item_id>')
def read_item(item_id):
return {'item_id': item_id}
3. Query Parameters
FastAPI:
@app.get('/items/')
def read_items(q: str = None):
return {'q': q}
Flask:
from flask import request
@app.route('/items')
def read_items():
q = request.args.get('q')
return {'q': q}
4. Request Body (JSON)
FastAPI:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post('/items/')
def create_item(item: Item):
return item
Flask:
from flask import request
@app.route('/items', methods=['POST'])
def create_item():
data = request.json
return data
5. Automatic Docs
FastAPI:
Built-in Swagger UI at /docs and ReDoc at /redoc
Flask:
Not built-in. Use Flask-RESTPlus, Flask-Swagger, etc.
6. Validation
FastAPI:
Built-in with Pydantic models
Flask:
Manual or use Marshmallow