Creating Scalable FastAPI Applications with Multiple Routers
Written on
Chapter 1: Introduction to FastAPI Applications
In the initial stages of developing a simple FastAPI application, you might find it straightforward to use a single file. Below is a basic example:
from fastapi import FastAPI
app = FastAPI()
@app.get('/') # Access via localhost:8000/
def test1():
return {'message': 'hello'}
@app.get('/test') # Access via localhost:8000/test
def test2():
return {'message': 'test'}
While it’s technically possible to condense everything into one .py file, this approach can quickly become cumbersome as your application expands. Maintaining a lengthy file can be challenging, particularly in an enterprise-level FastAPI setting.
Chapter 2: Understanding API Routers
To enhance the organization of your application, you can utilize API routers. This method allows for a more modular structure:
from fastapi import APIRouter, FastAPI
app = FastAPI()
router = APIRouter()
@router.get('/') # Access via localhost:8000/
def test1():
return {'msg': 'from test1'}
@router.get('/hello') # Access via localhost:8000/hello
def test2():
return {'msg': 'from test2'}
test_router = APIRouter(prefix='/test')
@test_router.get('/apple') # Access via localhost:8000/test/apple
def test3():
return {'msg': 'from test3'}
@test_router.get('/orange') # Access via localhost:8000/test/orange
def test4():
return {'msg': 'from test4'}
app.include_router(router)
app.include_router(test_router)
In this setup, routing is handled through APIRouter objects rather than the main app. Note that when using test_router, you must add a /test prefix to your endpoint, such as localhost:8000/test/apple.
Chapter 3: Refactoring for Scalability
Writing an extensive FastAPI application in a single file is generally not advisable. To improve readability and maintainability, consider dividing the code into multiple files. Here’s how you can structure your project:
- server.py - The main entry point
- home.py - Contains the main router
- test.py - Contains additional routes
server.py
from fastapi import FastAPI
app = FastAPI()
from home import router
from test import test_router
app.include_router(router)
app.include_router(test_router)
home.py
from fastapi import APIRouter
router = APIRouter()
@router.get('/')
def test1():
return {'msg': 'from test1'}
@router.get('/hello')
def test2():
return {'msg': 'from test2'}
test.py
from fastapi import APIRouter
test_router = APIRouter(prefix='/test')
@test_router.get('/apple')
def test3():
return {'msg': 'from test3'}
@test_router.get('/orange')
def test4():
return {'msg': 'from test4'}
By segmenting the code into different files, the readability significantly improves, making it easier to manage and navigate.
Chapter 4: Conclusion
In summary, if your application encompasses numerous endpoints, restructuring your codebase is essential. This guide serves as a helpful starting point for those looking to develop larger FastAPI applications.