A FastAPI utility to allow Controller Class usage
Project description
fastapi-router-controller
A FastAPI utility to allow Controller Class usage
Installation:
install the package
pip install fastapi-router-controller
How to use
Here we see a Fastapi CBV (class based view) application with class wide Basic Auth dependencies.
import uvicorn
from pydantic import BaseModel
from fastapi_router_controller import Controller
from fastapi import APIRouter, Depends, FastAPI, HTTPException, status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
router = APIRouter()
controller = Controller(router)
security = HTTPBasic()
def verify_auth(credentials: HTTPBasicCredentials = Depends(security)):
correct_username = credentials.username == "john"
correct_password = credentials.password == "silver"
if not (correct_username and correct_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect auth",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
class Foo(BaseModel):
bar: str = "wow"
async def amazing_fn():
return Foo(bar="amazing_variable")
@controller.resource()
class ExampleController:
# add class wide dependencies e.g. auth
dependencies = [Depends(verify_auth)]
# you can define in the Controller init some FastApi Dependency and them are automatically loaded in controller methods
def __init__(self, x: Foo = Depends(amazing_fn)):
self.x = x
@controller.route.get(
"/some_api", summary="A sample description", response_model=Foo
)
def sample_api(self):
print(self.x.bar) # -> amazing_variable
return self.x
# Load the controller to the main FastAPI app
app = FastAPI(
title="A sample application using fastapi_router_controller", version="0.1.0"
)
app.include_router(ExampleController.router())
uvicorn.run(app, host="0.0.0.0", port=9090)
Screenshot
All you expect from Fastapi
Also the login dialog
For some Example use-cases visit the example folder
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file fastapi-router-controller-0.5.0.tar.gz
.
File metadata
- Download URL: fastapi-router-controller-0.5.0.tar.gz
- Upload date:
- Size: 5.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.27.1 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.62.3 importlib-metadata/4.11.1 keyring/23.5.0 rfc3986/2.0.0 colorama/0.4.4 CPython/3.9.10
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | f4d385dff4aa2e54a768f2760391e99b3d74a2392aed020900328fa0c2d61b3c |
|
MD5 | dc0f6b9abc23905c3d657d207d719732 |
|
BLAKE2b-256 | d3ded96393be5b194fc01f94223fa4a810bc63512933ab7481e491af88f08ce8 |