/
), you can use the @app.route('/')
decorator.request
object from the flask
module to access incoming request data and the make_response
function to create responses.First, make sure you have Flask installed. You can install it using pip
:
pip install flask
Here is a simple Flask application example:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
Install FastAPI and Uvicorn (a server for running FastAPI applications):
pip install fastapi uvicorn
Here is the equivalent FastAPI application:
from fastapi import FastAPI
app = FastAPI()
@app.get('/')
def hello_world():
return {'message': 'Hello, World!'}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host='0.0.0.0', port=8000)
from flask import Flask
app = Flask(__name__)
@app.route('/items/<int:item_id>')
def get_item(item_id):
return f'Item ID: {item_id}'
from fastapi import FastAPI
app = FastAPI()
@app.get('/items/{item_id}')
def get_item(item_id: int):
return {'item_id': item_id}
In FastAPI, the type hint for item_id
ensures that the parameter is automatically converted to an integer and validated.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/add', methods=['POST'])
def add_numbers():
data = request.get_json()
num1 = data.get('num1')
num2 = data.get('num2')
result = num1 + num2
return jsonify({'result': result})
from fastapi import FastAPI, Request
from pydantic import BaseModel
app = FastAPI()
class Numbers(BaseModel):
num1: int
num2: int
@app.post('/add')
def add_numbers(numbers: Numbers):
result = numbers.num1 + numbers.num2
return {'result': result}
In FastAPI, the Numbers
Pydantic model is used to validate the incoming request data.
In Flask, data validation usually requires custom code. For example, to validate that a field in a JSON request is an integer:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/validate', methods=['POST'])
def validate():
data = request.get_json()
num = data.get('num')
if isinstance(num, int):
return jsonify({'message': 'Valid number'})
else:
return jsonify({'message': 'Invalid number'}), 400
FastAPI uses Pydantic models for data validation and serialization.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Number(BaseModel):
num: int
@app.post('/validate')
def validate(number: Number):
return {'message': 'Valid number'}
If the incoming data does not match the Number
model, FastAPI will automatically return a 422 Unprocessable Entity response.
Flask is synchronous by default. However, you can use extensions like Flask-Async
to support asynchronous operations.
from flask import Flask
import asyncio
app = Flask(__name__)
async def async_task():
await asyncio.sleep(1)
return 'Async task completed'
@app.route('/async')
async def async_route():
result = await async_task()
return result
FastAPI supports asynchronous programming natively.
from fastapi import FastAPI
import asyncio
app = FastAPI()
async def async_task():
await asyncio.sleep(1)
return 'Async task completed'
@app.get('/async')
async def async_route():
result = await async_task()
return {'result': result}
import unittest
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello'
class TestFlaskApp(unittest.TestCase):
def setUp(self):
app.testing = True
self.app = app.test_client()
def test_hello(self):
response = self.app.get('/')
self.assertEqual(response.data.decode('utf-8'), 'Hello')
if __name__ == '__main__':
unittest.main()
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get('/')
def hello():
return 'Hello'
client = TestClient(app)
def test_hello():
response = client.get('/')
assert response.status_code == 200
assert response.json() == 'Hello'
@app.errorhandler
decorator.@app.exception_handler
decorator to handle exceptions globally.Migrating from Flask to FastAPI can bring significant benefits in terms of performance, type safety, and asynchronous programming support. By following the steps outlined in this guide, you can smoothly transition your Flask application to a FastAPI application. Remember to take advantage of FastAPI’s powerful features like Pydantic models for data validation and asynchronous execution to build high - performance APIs.