Piccolo API Utilities

1.9.0 · active · verified Fri Apr 17

Piccolo API provides utilities for integrating the Piccolo ORM with ASGI applications. It includes essential ASGI middleware for common tasks like authentication (JWT, sessions, MFA) and rate limiting. The library is actively maintained, with regular releases (currently v1.9.0) addressing dependency updates, Python version support, and new features like Multi-Factor Authentication.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic Starlette application with JWT authentication using `piccolo-api`. It includes a public and a protected route, and shows how to configure `JWTAuth` middleware with a secret key and excluded paths. Remember to manage your secret keys securely, ideally via environment variables.

import os
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route

from piccolo_api import JWTAuth

# For demonstration, typically loaded from environment variables
SECRET_KEY = os.environ.get('JWT_SECRET_KEY', 'your_super_secret_key_here')

async def homepage(request):
    return JSONResponse({'hello': 'world'})

async def protected_route(request):
    return JSONResponse({'data': 'This is protected data!'})

routes = [
    Route('/', homepage),
    Route('/protected', protected_route)
]

middleware = [
    JWTAuth(
        secret_key=SECRET_KEY,
        # Exclude paths that don't require authentication
        excluded_paths=['/', '/docs'], 
        # Allow an endpoint to create a token for testing
        # In a real app, this would be a login endpoint
        get_token_response=lambda user_id: JSONResponse({'token': f'fake-jwt-token-for-{user_id}'})
    )
]

app = Starlette(routes=routes, middleware=middleware)

# To run this:
# uvicorn your_module_name:app --port 8000 --reload
# Access with: http://127.0.0.1:8000/
# Try http://127.0.0.1:8000/protected with a valid JWT in Authorization header
# You can use the get_token_response for generating a dummy token in dev.

view raw JSON →