How do I build a simple web API with Flask or FastAPI in Python?
· Category: Python Programming
Short answer
Flask and FastAPI are popular Python frameworks for building web APIs. Flask is minimal and extensible, while FastAPI offers automatic validation, serialization, and OpenAPI documentation based on type hints.
Steps
- Install the framework:
pip install flaskorpip install fastapi uvicorn. - Define routes that return JSON responses.
- Run the development server.
# Flask
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/api/hello")
def hello():
return jsonify({"message": "Hello, World!"})
if __name__ == "__main__":
app.run(debug=True)
# FastAPI
from fastapi import FastAPI
app = FastAPI()
@app.get("/api/hello")
def hello():
return {"message": "Hello, World!"}
Tips
- FastAPI's dependency injection system simplifies authentication, database sessions, and validation.
- Use
pydanticmodels with FastAPI for request and response schemas. - Flask's ecosystem is mature; FastAPI excels in async and auto-documentation.
Common issues
- Running Flask in production with
app.run(debug=True)is insecure; use Gunicorn or uWSGI instead. - FastAPI async routes must use
awaitfor I/O; blocking calls freeze the event loop. - Forgetting to handle CORS can cause frontend integration issues.