Routing in FastAPI groups endpoints by their URL paths. This helps organize the API logically, making it easier to maintain and understand. It does not automatically encrypt data or improve CPU usage directly.
from fastapi import FastAPI app = FastAPI() @app.get('/items') async def get_items(): return {'message': 'First'} @app.get('/items') async def get_items_duplicate(): return {'message': 'Second'}
When two routes have the same path and method, the second definition overwrites the first. FastAPI does not raise an error but uses the last defined function for that route.
from fastapi import FastAPI, APIRouter user_router = APIRouter() @user_router.get('/') async def read_users(): return ['Alice', 'Bob'] app = FastAPI() # Include router here
The correct method to add a router with a URL prefix is include_router. Other method names do not exist in FastAPI.
from fastapi import FastAPI, APIRouter api_router = APIRouter() @api_router.get('/items') async def get_items(): return {'items': [1, 2, 3]} app = FastAPI() app.include_router(api_router, prefix='/api/v1')
The router is included with prefix '/api/v1', so the full path is '/api/v1/items'. Accessing this returns the defined JSON with the list of items.
from fastapi import FastAPI, APIRouter product_router = APIRouter() @product_router.get('/products') async def list_products(): return ['apple', 'banana'] app = FastAPI() app.include_router(product_router, prefix='/store')
The router is included with prefix '/store', so the full path is '/store/products'. Accessing '/products' alone returns 404 because no route matches it.