Flask is a micro - framework for Python. It is minimalistic, meaning it provides only the essential components needed to build a web application, such as a request - response cycle, routing, and a simple templating engine. It gives developers a lot of freedom to choose other libraries and tools according to their project requirements. Flask is known for its simplicity and ease of learning, making it a great choice for beginners and small - scale projects.
FastAPI is a modern, fast (high - performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. It uses asynchronous programming and is built on top of Starlette for the web parts and Pydantic for data validation. FastAPI automatically generates interactive API documentation using Swagger UI and ReDoc, and it has built - in support for dependency injection, which makes it easy to manage complex application logic.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
In this code, we first import the Flask
class from the flask
module. Then we create an instance of the Flask
class named app
. We define a route using the @app.route
decorator, which maps the root URL (/
) to the hello_world
function. Finally, we run the application in debug mode.
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def read_root():
return {"Hello": "World"}
Here, we import the FastAPI
class from the fastapi
module. We create an instance of FastAPI
named app
. We use the @app.get
decorator to define a route for the root URL (/
), and the function read_root
returns a JSON response.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/hello')
def hello():
return 'Hello, World!'
In Flask, we use the @app.route
decorator to define different routes. Each route is associated with a function that returns the response to be sent to the client.
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def read_root():
return {"message": "Root page"}
@app.get('/items/{item_id}')
def read_item(item_id: int):
return {"item_id": item_id}
FastAPI uses decorators like @app.get
, @app.post
, etc., to define routes. It also supports path parameters, as shown in the read_item
function, where item_id
is a path parameter of type int
.
from flask import Flask, request
app = Flask(__name__)
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
return f'Username: {username}, Password: {password}'
In Flask, we can access the request data using the request
object. Here, we are handling a POST request and extracting the username
and password
from the form data.
from fastapi import FastAPI, Body
app = FastAPI()
@app.post('/login')
def login(username: str = Body(...), password: str = Body(...)):
return {"username": username, "password": password}
In FastAPI, we can use the Body
class to handle request body data. The ...
indicates that the parameter is required.
gunicorn -w 4 -b 0.0.0.0:8000 app:app
where app
is the name of your Flask application file.async def
for functions that involve I/O - bound operations such as database queries or API calls.from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get('/async')
async def async_route():
await asyncio.sleep(1)
return {"message": "Async operation completed"}
Flask and FastAPI are both excellent Python web frameworks, but they serve different purposes. Flask is a great choice for beginners and small - scale projects where simplicity and flexibility are key. It allows developers to have full control over the application stack and choose the libraries they need. On the other hand, FastAPI is designed for high - performance API development. It offers automatic documentation generation, type - checking, and asynchronous programming support, making it ideal for large - scale projects and applications that require fast response times.