Auto-Generated API Reference¶
This page provides auto-generated documentation from the source code docstrings using mkdocstrings.
For hand-written endpoint guides, see the other pages in the API Reference section.
Configuration¶
file_organizer.api.config ¶
API configuration and settings loader.
Classes¶
ApiSettings ¶
Bases: BaseModel
Settings for the FastAPI backend.
Functions¶
load_settings() ¶
Load API settings from a config file and environment variables.
Environment variables override config file values when present. Delegates to specialized loaders for each configuration category to keep complexity manageable.
Returns:
| Type | Description |
|---|---|
ApiSettings | Validated |
Raises:
| Type | Description |
|---|---|
ValueError | On critical production misconfigurations. |
Source code in src/file_organizer/api/config.py
Authentication¶
file_organizer.api.auth ¶
Authentication helpers for JWT and password hashing.
Classes¶
TokenError ¶
Bases: Exception
Raised when a JWT token is invalid.
TokenBundle(access_token, refresh_token, access_jti, refresh_jti, access_expires_at, refresh_expires_at) dataclass ¶
Bundle of access and refresh tokens.
Functions¶
verify_password(plain_password, hashed_password) ¶
Return True if plain_password matches hashed_password.
Source code in src/file_organizer/api/auth.py
hash_password(password) ¶
validate_password(password, settings) ¶
Validate password strength based on API settings.
Source code in src/file_organizer/api/auth.py
create_token_bundle(user_id, username, settings) ¶
Create a new access and refresh token bundle for a user.
Source code in src/file_organizer/api/auth.py
decode_token(token, settings) ¶
Decode and return the JWT payload, raising TokenError if invalid.
Source code in src/file_organizer/api/auth.py
is_access_token(payload) ¶
API Key Management¶
file_organizer.api.api_keys ¶
API key helpers for external integrations.
Functions¶
generate_api_key(prefix='fo') ¶
hash_api_key(api_key) ¶
match_api_key_hash(api_key, hashes) ¶
Return the stored hash matching an API key, if any.
Source code in src/file_organizer/api/api_keys.py
verify_api_key(api_key, hashes) ¶
api_key_identifier(api_key, hashes) ¶
Return a stable identifier derived from the stored hash.
Source code in src/file_organizer/api/api_keys.py
Rate Limiting¶
file_organizer.api.rate_limit ¶
Rate limiting helpers for API requests.
Classes¶
RateLimitResult(allowed, remaining, reset_at) dataclass ¶
Result of a rate limit check.
RateLimiter ¶
RateLimitState(count, reset_at) dataclass ¶
Mutable rate limit state for a single key.
InMemoryRateLimiter(max_entries=10000, sweep_interval_seconds=60) ¶
Simple in-memory fixed-window rate limiter.
Initialize InMemoryRateLimiter with given capacity and sweep interval.
Source code in src/file_organizer/api/rate_limit.py
Functions¶
check(key, limit, window_seconds) ¶
Check rate limit for key and return the result.
Source code in src/file_organizer/api/rate_limit.py
RedisRateLimiter(redis, prefix='ratelimit:') ¶
Redis-backed fixed-window rate limiter.
Initialize RedisRateLimiter with a Redis client and key prefix.
Source code in src/file_organizer/api/rate_limit.py
Functions¶
check(key, limit, window_seconds) ¶
Check rate limit for key against Redis and return the result.
Source code in src/file_organizer/api/rate_limit.py
Functions¶
build_rate_limiter(redis_url) ¶
Create a rate limiter instance.
Source code in src/file_organizer/api/rate_limit.py
Authentication Rate Limiting¶
file_organizer.api.auth_rate_limit ¶
Login rate limiting helpers.
Classes¶
LoginRateLimiter ¶
RateLimitState(count, expires_at) dataclass ¶
Track rate limit count and expiry for a key.
InMemoryLoginRateLimiter(max_attempts, window_seconds, _state=dict()) dataclass ¶
In-memory fixed-window rate limiter for login attempts.
Functions¶
is_blocked(key) ¶
Return whether the key is currently blocked and retry-after seconds.
Source code in src/file_organizer/api/auth_rate_limit.py
record_failure(key) ¶
Record a failed attempt and return blocked status and retry-after seconds.
Source code in src/file_organizer/api/auth_rate_limit.py
RedisLoginRateLimiter(redis, max_attempts, window_seconds, prefix='auth:login:') dataclass ¶
Redis-backed fixed-window login rate limiter.
Functions¶
is_blocked(key) ¶
Return whether the key is currently blocked and retry-after seconds.
Source code in src/file_organizer/api/auth_rate_limit.py
record_failure(key) ¶
Record a failed attempt and return blocked status and retry-after seconds.
Source code in src/file_organizer/api/auth_rate_limit.py
Functions¶
build_login_rate_limiter(redis_url, max_attempts, window_seconds) ¶
Create a login rate limiter, preferring Redis when configured.
Source code in src/file_organizer/api/auth_rate_limit.py
Token Store¶
file_organizer.api.auth_store ¶
Token storage for authentication sessions.
Classes¶
TokenStore ¶
InMemoryTokenStore() ¶
Simple in-memory token store for testing or local fallback.
Initialize InMemoryTokenStore with empty refresh and revoked buckets.
Source code in src/file_organizer/api/auth_store.py
RedisTokenStore(redis, refresh_prefix='auth:refresh:', revoked_prefix='auth:revoked:') dataclass ¶
Functions¶
build_token_store(redis_url) ¶
Create a token store, preferring Redis when configured.
Source code in src/file_organizer/api/auth_store.py
Caching¶
file_organizer.api.cache ¶
Cache abstraction for API persistence layers.
Provides a small key/value interface with an in-memory implementation and an optional Redis backend.
Classes¶
CacheBackend ¶
InMemoryCache() ¶
In-process TTL cache implementation.
Thread-safe: all access to _entries is protected by a lock.
Initialize InMemoryCache with empty entries dict.
Source code in src/file_organizer/api/cache.py
RedisCache(redis_url) ¶
Redis-backed cache implementation.
Initialize RedisCache with a connection to redis_url.
Source code in src/file_organizer/api/cache.py
Functions¶
build_cache_backend(redis_url) ¶
Build a cache backend from configuration.
Falls back to in-memory cache when Redis is unavailable or connection validation fails.
Source code in src/file_organizer/api/cache.py
Middleware¶
file_organizer.api.middleware ¶
Middleware setup for the API layer.
Classes¶
RateLimitMiddleware(app, settings, limiter) ¶
Bases: BaseHTTPMiddleware
Apply rate limiting based on endpoint and client identity.
Initialize RateLimitMiddleware with app, settings, and limiter.
Source code in src/file_organizer/api/middleware.py
Functions¶
dispatch(request, call_next) async ¶
Process an HTTP request through the rate limiter.
Source code in src/file_organizer/api/middleware.py
SecurityHeadersMiddleware(app, settings) ¶
Bases: BaseHTTPMiddleware
Attach security headers to API responses.
Initialize SecurityHeadersMiddleware with app and settings.
Source code in src/file_organizer/api/middleware.py
Functions¶
dispatch(request, call_next) async ¶
Process an HTTP request and attach security headers to the response.
Source code in src/file_organizer/api/middleware.py
Functions¶
setup_middleware(app, settings) ¶
Configure middleware on the FastAPI app.
Source code in src/file_organizer/api/middleware.py
Dependencies¶
file_organizer.api.dependencies ¶
Dependency providers for the API layer.
Classes¶
AnonymousUser(id='anonymous', username='anonymous', email='anonymous@example.com', full_name=None, is_active=True, is_admin=False, created_at=(lambda: datetime.now(UTC))(), last_login=None) dataclass ¶
Anonymous user identity used when auth is disabled.
ApiKeyIdentity(id, username, email='api-key@example.com', full_name=None, is_active=True, is_admin=False, created_at=(lambda: datetime.now(UTC))(), last_login=None, auth_type='api_key') dataclass ¶
API key-based user identity.
Functions¶
get_settings() cached ¶
get_config_manager() cached ¶
Return a config manager, optionally overridden by FO_CONFIG_DIR.
get_db(settings=Depends(get_settings)) ¶
Yield a database session for auth data.
Source code in src/file_organizer/api/dependencies.py
get_token_store(settings=Depends(get_settings)) ¶
get_login_rate_limiter(settings=Depends(get_settings)) ¶
Return the login rate limiter for the current settings.
Source code in src/file_organizer/api/dependencies.py
get_current_user(request, token=Depends(oauth2_scheme), settings=Depends(get_settings), db=Depends(get_db), token_store=Depends(get_token_store)) ¶
Resolve and return the current authenticated user.
Source code in src/file_organizer/api/dependencies.py
get_current_active_user(user=Depends(get_current_user), settings=Depends(get_settings)) ¶
Return the current user, raising 400 if inactive.
Source code in src/file_organizer/api/dependencies.py
require_admin_user(user=Depends(get_current_active_user), settings=Depends(get_settings)) ¶
Return the current user, raising 403 if not an admin.
When settings.auth_enabled is False the admin check is bypassed and user is returned unconditionally. HTTPException(403) is raised only when auth is enabled and user.is_admin is False.
Source code in src/file_organizer/api/dependencies.py
Utilities¶
file_organizer.api.utils ¶
Shared helpers for API routers.
Classes¶
Functions¶
resolve_path(path_value, allowed_paths=None) ¶
Expand and normalize a filesystem path, then enforce allowed-root policy.
Uses Path.resolve() + Path.is_relative_to() to evaluate containment, which correctly handles symlinks, .. sequences, and Windows drive-qualified paths — unlike a bare str.startswith or os.path.commonpath comparison.
Source code in src/file_organizer/api/utils.py
file_info_from_path(path) ¶
Build FileInfo from a filesystem path, raising ApiError on failure.
Source code in src/file_organizer/api/utils.py
Exceptions¶
file_organizer.api.exceptions ¶
Exception handlers for the API layer.
Classes¶
ApiError(status_code, error, message, details=None) dataclass ¶
Functions¶
setup_exception_handlers(app) ¶
Register exception handlers on the app.
Source code in src/file_organizer/api/exceptions.py
OpenAPI Response Helpers¶
file_organizer.api.openapi_responses ¶
Shared OpenAPI response metadata for REST endpoints.
Classes¶
Functions¶
success_response(description, example, *, status_code=200) ¶
Build a documented success response with an example object or array payload.
Source code in src/file_organizer/api/openapi_responses.py
api_error_response(status_code, *, error, message, description=None, details=None, example_name=None) ¶
Build an ApiError-style response entry with a named OpenAPI example.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
status_code | int | HTTP status code for this response variant. | required |
error | str | Machine-readable error slug (also used as the default example name). | required |
message | str | Human-readable description of the error. | required |
description | str | None | Optional override for the response-level description line. | None |
details | Any | None | Optional extra payload attached under | None |
example_name | str | None | Key used in the | None |
Returns:
| Type | Description |
|---|---|
OpenAPIResponses | Single-entry |
OpenAPIResponses |
|
OpenAPIResponses | same-status variants side-by-side. |
Source code in src/file_organizer/api/openapi_responses.py
detail_error_response(status_code, *, detail, description=None) ¶
Build a FastAPI HTTPException-style response entry.
Source code in src/file_organizer/api/openapi_responses.py
validation_error_response() ¶
Build the standard request validation error response entry.
Source code in src/file_organizer/api/openapi_responses.py
merge_responses(*response_sets) ¶
Merge multiple OpenAPI response maps, preserving same-status variants.
For each status code:
- If only one response set defines it, the entry is used as-is.
- If multiple sets define the same status code and both entries carry a
content["application/json"]["examples"]dict (as produced by :func:api_error_response), their example dicts are merged so that every named variant is retained. - Otherwise (e.g. a
success_responsethat uses"example"singular) the later entry wins, matching the previousdict.updatesemantics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*response_sets | OpenAPIResponses | Zero or more | () |
Returns:
| Type | Description |
|---|---|
OpenAPIResponses | A single merged |
Source code in src/file_organizer/api/openapi_responses.py
Authentication Models¶
file_organizer.api.auth_models ¶
SQLAlchemy models for API authentication.
Server¶
file_organizer.api.main ¶
FastAPI application entrypoint.
Classes¶
Functions¶
configure_logging(settings) ¶
Configure structured logging to console and file.
Source code in src/file_organizer/api/main.py
create_app(settings=None) ¶
Create the FastAPI application.
Source code in src/file_organizer/api/main.py
get_app() ¶
Get or create the FastAPI application instance (thread-safe).
This function implements lazy initialization with thread safety to avoid: - Import-time side effects (creating .config directories) - Multiple app instances due to race conditions in multi-threaded contexts - Test isolation issues in concurrent test environments
The first call to this function will trigger app creation via create_app(). Subsequent calls return the cached instance. Thread-safe via lock protection.
Intended for: Test infrastructure, application startup hooks, ASGI servers with multiple worker threads
Returns:
| Type | Description |
|---|---|
FastAPI | The initialized and cached FastAPI application instance. |