Skip to main content

Routes Manager for FastAPI

Manipulate requests before FastAPI processes them (even before middlewares), and responses once finished.

Installation

$ pip install fastapi-routesmanager

Example

Using example HeadersLogger from this package.

from typing import Union

from fastapi import FastAPI

from fastapi_routesmanager import HeadersLogger, RouteManagersRegistry, ManagedAPIRouter
import logging

logging.basicConfig(level=logging.DEBUG)  # Needed to get DEBUG output

RouteManagersRegistry.register_route_manager(HeadersLogger)  # Register manager

app = FastAPI()

router = ManagedAPIRouter()


@router.get("/")  # Use router instead of app
def read_root():
    return {"Hello": "World"}


@router.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}


app.include_router(router)  # Include the router to the app
Or you can register multiple managers at once
RouteManagersRegistry.register_route_managers([
    HeadersLogger,
    ExceptionLogger
])

Run it

$ uvicorn main:app --reload

Check it

Browse to http://127.0.0.1:8000 and check the server console. You should see something like this showing the headers

# DEBUG:headers_logger:Requests headers: Headers({'host': 'localhost:8000', 'user-agent': 'Mozilla Firefox', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'accept-language': 'es-AR,es;q=0.8,en-US;q=0.5,en;q=0.3', 'accept-encoding': 'gzip', 'dnt': '1', 'connection': 'keep-alive', 'upgrade-insecure-requests': '1', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none'})
# DEBUG:headers_logger:Response headers: MutableHeaders({'content-length': '17', 'content-type': 'application/json'})
# INFO:     127.0.0.1:49370 - "GET /1 HTTP/1.1" 200 OK

Creating custom Manager

In order to create a custom manager you need to extend RouteManager and declare an async def run(...) method.

Within this method you can access the request, execute it and get the response.

from fastapi_routesmanager import RouteManager
from starlette.requests import Request
from starlette.responses import Response
from typing import Callable, List, Type, Optional


class CustomManager(RouteManager):
    async def run(
            self,
            request: Request,
            call_next: Callable,
            remaining_managers: List[Type[RouteManager]],
    ) -> Optional[Response]:
        # This will run the request through FastAPI  
        response: Response = await call_next(request, remaining_managers)
        return response

In the remaining_managers list you will find all remaining managers to be run. You can modify this list to add or remove managers dynamically.

Metadata

Release files for fastapi-routesmanager 0.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fastapi-routesmanager 0.0.3
File Size Uploaded
fastapi_routesmanager-0.0.3.tar.gz 3.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fastapi-routesmanager 0.0.3
File Interpreter ABI Platform
fastapi_routesmanager-0.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 8.6 kB

Release files / fastapi_routesmanager-0.0.3.tar.gz

Download URL fastapi_routesmanager-0.0.3.tar.gz
Size 3.7 kB
Tags Source
SHA-256 checksum
How to use checksums
ef2a258c0c70061de03a982c01f463d63d15e76eea114a20e9a1ac6759d96b8d
BLAKE2b-256 checksum
How to use checksums
c273118fdfb80eb93be64e5efdaa9a3630e9e916f9017732f4e4ca1b522cf4ea
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.18

Release files / fastapi_routesmanager-0.0.3-py3-none-any.whl

Download URL fastapi_routesmanager-0.0.3-py3-none-any.whl
Size 4.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2f7055c702c1883442b1985b10454cd5dc68866962a3c568f39b11333ace86a9
BLAKE2b-256 checksum
How to use checksums
996f780038c28bbc788d60751e4c59219bc59ab914530b8964f0ec5465d4e321
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.18

Release history Release notifications | RSS feed

This release

0.0.3 This release

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page