Package: fastapi-controllers
fastapi-controllersA simple solution for organizing your FastAPI endpointsOrganize your API endpointsfastapi-controllersoffers a simple solution for organizing your API endpoints by means of aControllerclass embracing the concept of class-based views.Featuresclass-based approach to organizing FastAPI endpointsclass-scoped definition of APIRouter parametersinstance-scoped definition of FastAPI dependenciesit integrates seamlessly with the FastAPI frameworkworks with both sync and async endpointsInstallationpipinstallfastapi-controllersMinimal working exampleimportuvicornfromfastapiimportFastAPI,Response,statusfromfastapi.websocketsimportWebSocketfromfastapi_controllersimportController,get,websocketclassExampleController(Controller):@get("/example",response_class=Response)asyncdefget_example(self)->Response:returnResponse(status_code=status.HTTP_200_OK)@websocket("/ws")asyncdefws_example(websocket:WebSocket)->None:awaitwebsocket.accept()whileTrue:data=awaitwebsocket.receive_text()awaitwebsocket.send_text(f"Received:{data}")if__name__=="__main__":app=FastAPI()app.include_router(ExampleController.create_router())uvicorn.run(app)FastAPI'sAPIRouteris created and populated with API routes by theController.create_routermethod and can be incorporated into the application in the usual way viaapp.include_router.Seamless integrationThe router-related parameters as well as those of HTTP request-specific and websocket decorators are expected to be the same as those used byfastapi.APIRouter,fastapi.APIRouter.<request_method>andfastapi.APIRouter.websocket. Validation of the provided parameters is performed during initialization via theinspectmodule. This ensures compatibility with the FastAPI framework and prevents the introduction of a new, unnecessary naming convention.Available decoratorsfromfastapi_controllersimportdelete,get,head,options,patch,post,put,trace,websocketUse class variables to customize your APIRouterClass variables can be used to set the commonly used APIRouter parameters:prefix,dependenciesandtags.importuvicornfromfastapiimportDepends,FastAPI,Response,statusfromfastapi.securityimportHTTPBasic,HTTPBasicCredentialsfrompydanticimportBaseModelfromfastapi_controllersimportController,get,postsecurity=HTTPBasic()asyncdefauthorized_user(credentials:HTTPBasicCredentials=Depends(security))->None:...classExampleRequest(BaseModel):name:strclassExampleResponse(BaseModel):message:strclassExampleController(Controller):prefix="/example"tags=["example"]dependencies=[Depends(authorized_user)]@get("",response_class=Response)asyncdefget_example(self)->Response:returnResponse(status_code=status.HTTP_200_OK)@post("",response_model=ExampleResponse)asyncdefpost_example(self,data:ExampleRequest)->ExampleResponse:returnExampleResponse(message=f"Hello,{data.name}!")if__name__=="__main__":app=FastAPI()app.include_router(ExampleController.create_router())uvicorn.run(app)Additional APIRouter parametersAdditional APIRouter parameters can be provided via the__router_params__class variable in form of a mapping.importuvicornfromfastapiimportFastAPI,Response,statusfromfastapi_controllersimportController,getclassExampleController(Controller):prefix="/example"tags=["example"]__router_params__={"deprecated":True}@get("",response_class=Response)asyncdefget_example(self)->Response:returnResponse(status_code=status.HTTP_200_OK)if__name__=="__main__":app=FastAPI()app.include_router(ExampleController.create_router())uvicorn.run(app):warning:Important: Beware of assigning values to the same parameter twice (directly on class-level and through__router_params__). The values stored in__router_params__have precedence and will override your other settings if a name conflict arises. E.g. the followingControllerwould create anAPIRouterwithprefix=/override,tags=["override"]anddependencies=[Depends(override)]fromfastapiimportDependsfromfastapi_controllersimportControllerclassExampleController(Controller):prefix="/example"tags=["example"]dependencies=[Depends(example)]__router_params__={"prefix":"/override","tags":["override"],"dependencies":[Depends(override)],}Instance-scoped dependenciesInstance-scoped attributes can be defined in the__init__method of theControllerand offer an easy way to access common dependencies for all endpoints.importjsonimportuvicornfromfastapiimportDepends,FastAPI,Response,statusfromfastapi_controllersimportController,getclassDbSession:@propertydefstatus(self)->str:return"CONNECTED"asyncdefget_db_session()->DbSession:returnDbSession()classExampleController(Controller):prefix="/example"def__init__(self,session:DbSession=Depends(get_db_session))->None:self.session=session@get("",response_class=Response)asyncdefget_status(self)->Response:returnResponse(content=json.dumps({"status":f"{self.session.status}"}),status_code=status.HTTP_200_OK,media_type="application/json",)if__name__=="__main__":app=FastAPI()app.include_router(ExampleController.create_router())uvicorn.run(app)