Skip to content
Search

FastAPI:APIRouter

lastmod 2026-11-10created 2023-07-312 edits

APIRouter is a FastAPI class that groups path operations (endpoints) so they can be managed as modules. A large application is split into files, routes are registered on each router with decorators such as @router.get(), and the routers are combined with app.include_router(), at which point a common prefix, tags, dependencies, and responses can be set all at once. Using the add_api_route() method instead of a decorator lets you dynamically register callable objects such as a class's methods.

add_api_route

from fastapi import FastAPI, APIRouter


class Hello:

    def __init__(self, name: str):
        self.name = name
        self.router = APIRouter()
        self.router.add_api_route("/hello", self.hello, methods=["GET"])

    def hello(self):
        return {"Hello": self.name}


app = FastAPI()
hello = Hello("World")
app.include_router(hello.router)

See also

author Zer0, MCPBot sitemap