fastapi-utils

repository·master·Indexed 25 days ago

https://github.com/fastapiutils/fastapi-utils

A collection of developer tools and reusable utilities for FastAPI designed to reduce boilerplate and increase code reuse. Key features include Class-Based Views (@cbv), a Resource class for OOP-based CRUD operations, APIModel for automatic snake_case and camelCase handling, APISettings for environment-based configuration, and specialized utilities for SQLAlchemy sessions and GUID types.

Tokens
7.4K
Snippets
6
Records
55
Agent score
79%

What's inside fastapi-utils

  1. Overview of fastapi-utils features

    master

    fastapi-utils provides utilities to reduce boilerplate in FastAPI projects. Key features include:

    FastAPI Integration Utilities

    • Resource Class: An OOP-based base class for implementing CRUD operations quickly.
    • Class Based Views: Allows grouping related endpoints to avoid repeating dependencies in function signatures.
    • Repeated Tasks: Utility to trigger periodic tasks automatically on server startup.
    • Timing Middleware: Middleware that logs basic timing information for every incoming request.
    • OpenAPI Spec Simplification: Simplifies OpenAPI Operation IDs to produce cleaner output when using OpenAPI Generator.
    • SQLAlchemy Sessions: Provides FastAPISessionMaker for customizable SQLAlchemy Session dependencies.

    General Utilities

    • APIModel: A pydantic.BaseModel derivative with useful defaults.
    • APISettings: A pydantic.BaseSettings subclass for configuring FastAPI via environment variables.
    • String-Valued Enums: StrEnum and CamelStrEnum for easier maintenance of string-based enums.
    • CamelCase Conversions: Functions to convert strings between snake_case, camelCase, and PascalCase.
    • GUID Type: A specialized type for using UUIDs as primary keys in database tables.
  2. Custom initialization in Class-Based Views

    master

    You can define an __init__ method in a @cbv decorated class to perform custom instance-initialization logic.

    Key behaviors:

    • Dependency Injection: Arguments to the __init__ method are injected by FastAPI using the same mechanism as standard route functions.
    • Attribute Precedence: Annotated instance attributes (shared dependencies) are set on the class instance before the __init__ method is called.
    • Constraint: Do not use __init__ argument names that are identical to your annotated instance attribute names to avoid confusion, although you can still safely access the pre-set attributes via self inside __init__.
  3. Enable ORM mode with APIModel

    master
    The APIModel class comes pre-configured with Pydantic's orm_mode (or from_attributes in newer Pydantic versions). This allows FastAPI to automatically serialize objects that are not standard dictionaries—such as SQLAlchemy ORM models—into the specified response_model, provided the object has attributes that match the model's field names.
  4. Simplify OpenAPI operation IDs with simplify_operation_ids

    master

    By default, FastAPI generates operationIds by combining the function name, endpoint path, and request method (e.g., getResourceApiV1ResourceResourceIdGet). While this prevents collisions, it results in extremely verbose function names in auto-generated API clients.

    You can use fastapi_utils.openapi.simplify_operation_ids to change this behavior so that operationIds are generated using only the function name.

    Warning: When using this method, you must ensure that every endpoint/method combination uses a unique function name to avoid conflicting operationIds in your OpenAPI specification.

  5. Create CRUD resources using the Resource class

    master
    If you prefer an Object-Oriented Programming (OOP) approach similar to Flask-RESTful, you can use the Resource class to build CRUD applications. To use it, create a class that inherits from Resource and define your methods (e.g., get, post, put, delete). You then register this resource with your FastAPI application using standard routing or the provided API integration.
  6. Schedule periodic tasks with `@repeat_every`

    master

    Use the @repeat_every decorator from fastapi_utils.tasks to run a function periodically. To ensure the task runs automatically when the server starts and continues while the server is running, combine it with FastAPI's @app.event("startup") decorator.

    Key Behaviors:

    • Function Signature: The wrapped function must not take any required arguments.
    • Async/Sync Support: Works with both async def and regular def functions.
    • Blocking IO: If using a regular def function, repeat_every executes it in a threadpool to avoid blocking the event loop.
    • Lifecycle: When combined with a startup event, the loop starts during startup and runs in the background without preventing the server from finishing its startup sequence.
  7. Use the `@cbv` decorator for Class-Based Views

    master

    The @cbv decorator from fastapi_utils.cbv allows you to consolidate endpoint signatures and reduce boilerplate by sharing dependencies across multiple related routes within a class. Instead of repeating the same Depends arguments in every function signature, you define them once as class attributes.

    To implement Class-Based Views:

    1. Create an APIRouter instance.
    2. Define a class where the methods will serve as endpoints.
    3. Decorate the class with @cbv(router).
    4. Define shared dependencies as class attributes using Depends.
    5. Access these dependencies within your methods using self.attribute_name.

    Each endpoint method signature should then only include parameters specific to that individual endpoint.

  8. Install fastapi-utils

    master

    You can install fastapi-utils using pip. Depending on your needs, you can choose between a slim installation or one that includes extra dependencies for SQLAlchemy or the full suite of features.

    • Basic installation: Installs only the core utilities.
    • Session support: Includes the FastAPISessionMaker for SQLAlchemy sessions.
    • Full installation: Includes all available packages and features.
    pip install fastapi-utils  # For basic slim package :)
    
    pip install fastapi-utils[session]  # To add sqlalchemy session maker
    
    pip install fastapi-utils[all]  # For all the packages
  9. Use `get_api_settings` to configure a `FastAPI` instance

    master

    To efficiently manage configuration, use the get_api_settings function. This function is decorated with lru_cache, meaning the environment variables are parsed only once and then cached for high performance when accessed in endpoint functions.

    Best Practices

    1. Initialize FastAPI in a function: This prevents access to partially-configured instances and facilitates testing.
    2. Clear cache during app creation: If you are creating a new app instance (e.g., in a test suite), call get_api_settings.cache_clear() to ensure the settings are reloaded from the environment.
    3. Apply settings via fastapi_kwargs: Pass the dictionary from api_settings.fastapi_kwargs directly into the FastAPI constructor.

    Example implementation:

  10. Convert between snake_case and camelCase using fastapi_utils.camelcase

    master

    The fastapi_utils.camelcase module provides utility functions to convert strings between snake_case (standard Python convention) and camelCase or PascalCase (standard JSON/JavaScript convention).

    These utilities are useful for:

    1. API Models: Ensuring your Python code uses snake_case while external JSON payloads use camelCase (often used via APIModel).
    2. Database Mapping: Ensuring SQLAlchemy table names or columns follow snake_case even if the source data uses different casing.