Core Modules Reference¶
Reference documentation for Apiary's core modules.
Authentication¶
Authentication Module¶
core.auth.authentication
¶
Authentication utilities for API key validation.
AuthenticatedUser
¶
Represents an authenticated user.
Initialize authenticated user.
Parameters:
-
api_key(str) –The validated API key
Source code in core/auth/authentication.py
get_api_key_from_header
async
¶
Extract API key from request header.
Parameters:
-
x_api_key(str | None, default:Header(None, alias='X-API-Key')) –API key from X-API-Key header
Returns:
-
str | None–API key string or None if not provided
Source code in core/auth/authentication.py
validate_api_key
¶
Validate an API key against configured keys.
Parameters:
-
api_key(str) –The API key to validate
-
settings(Settings) –Application settings containing global API keys
-
endpoint_keys(str | None, default:None) –Optional endpoint-specific API keys (overrides global keys)
Returns:
-
bool–True if the API key is valid, False otherwise
Source code in core/auth/authentication.py
create_api_key_validator
¶
Create an API key validator dependency with optional endpoint-specific keys.
Parameters:
-
endpoint_keys(str | None, default:None) –Optional endpoint-specific API keys
Returns:
-
–
A dependency function for API key validation
Source code in core/auth/authentication.py
verify_api_key
async
¶
verify_api_key(
api_key: str | None = Depends(get_api_key_from_header),
settings: Settings = Depends(get_settings),
) -> str
Default dependency to verify API key authentication using global keys.
Parameters:
-
api_key(str | None, default:Depends(get_api_key_from_header)) –API key from request header
-
settings(Settings, default:Depends(get_settings)) –Application settings
Returns:
-
str–The validated API key
Raises:
-
HTTPException–If authentication fails
Source code in core/auth/authentication.py
create_optional_authenticator
¶
Create an optional authenticator with endpoint-specific keys.
Parameters:
-
endpoint_keys(str | None, default:None) –Optional endpoint-specific API keys
Returns:
-
–
A dependency function for optional authentication
Source code in core/auth/authentication.py
get_authenticated_user
async
¶
get_authenticated_user(
api_key: str | None = Depends(get_api_key_from_header),
settings: Settings = Depends(get_settings),
) -> AuthenticatedUser | None
Get authenticated user from API key (optional) using global keys.
This function does not raise an error if authentication fails. It returns None if the API key is missing or invalid.
Parameters:
-
api_key(str | None, default:Depends(get_api_key_from_header)) –API key from header (may be None)
-
settings(Settings, default:Depends(get_settings)) –Application settings
Returns:
-
AuthenticatedUser | None–AuthenticatedUser if authenticated, None otherwise
Source code in core/auth/authentication.py
Authorization Module¶
core.auth.authorization
¶
Authorization utilities for access control.
create_auth_dependency
¶
Create an auth dependency with optional endpoint-specific keys.
Parameters:
-
endpoint_keys(str | None, default:None) –Optional endpoint-specific API keys
Returns:
-
–
A dependency function that requires authentication
Source code in core/auth/authorization.py
require_auth
async
¶
Dependency that requires authentication (using global keys).
This dependency will raise an AuthenticationError if the request is not authenticated.
Parameters:
-
api_key(str, default:Depends(verify_api_key)) –Validated API key
Returns:
-
AuthenticatedUser–AuthenticatedUser instance
Raises:
-
AuthenticationError–If authentication fails
Source code in core/auth/authorization.py
Exceptions¶
core.exceptions
¶
Custom exception classes for the API.
APIError
¶
APIError(
message: str,
status_code: int = 500,
details: dict[str, Any] | None = None,
error_code: str | None = None,
)
Bases: Exception
Base exception for all API errors.
Initialize API exception.
Parameters:
-
message(str) –Human-readable error message
-
status_code(int, default:500) –HTTP status code
-
details(dict[str, Any] | None, default:None) –Additional error details
-
error_code(str | None, default:None) –Optional error code for programmatic handling
Source code in core/exceptions.py
ValidationError
¶
Bases: APIError
Exception for validation errors.
Initialize validation error.
Parameters:
-
message(str) –Error message
-
status_code(int, default:400) –HTTP status code (default: 400)
-
details(dict[str, Any] | None, default:None) –Additional error details
Source code in core/exceptions.py
NotFoundError
¶
Bases: APIError
Exception for resource not found errors.
Initialize not found error.
Parameters:
-
message(str, default:'Resource not found') –Error message
-
details(dict[str, Any] | None, default:None) –Additional error details
Source code in core/exceptions.py
AuthenticationError
¶
AuthenticationError(
message: str = "Authentication required",
details: dict[str, Any] | None = None,
)
Bases: APIError
Exception for authentication errors.
Initialize authentication error.
Parameters:
-
message(str, default:'Authentication required') –Error message
-
details(dict[str, Any] | None, default:None) –Additional error details
Source code in core/exceptions.py
AuthorizationError
¶
AuthorizationError(
message: str = "Insufficient permissions",
details: dict[str, Any] | None = None,
)
Bases: APIError
Exception for authorization errors.
Initialize authorization error.
Parameters:
-
message(str, default:'Insufficient permissions') –Error message
-
details(dict[str, Any] | None, default:None) –Additional error details
Source code in core/exceptions.py
Services¶
Base Service¶
core.services.base
¶
Base service interface for extensible services.
BaseService
¶
Bases: ABC
Base class for all services.
Initialize service.
Parameters:
-
http_client(AsyncClient | None, default:None) –Optional HTTP client (will create one if not provided)
Source code in core/services/base.py
call
abstractmethod
async
¶
Call the service with given parameters.
Parameters:
-
parameters(dict[str, Any] | None, default:None) –Service parameters
Returns:
-
dict[str, Any]–Service response as dictionary
Raises:
-
Exception–If service call fails
Source code in core/services/base.py
get_http_client
async
¶
Get HTTP client (creates one if needed).
Returns:
-
AsyncClient–httpx.AsyncClient instance
Source code in core/services/base.py
cleanup
async
¶
API Key Management¶
API Key Manager¶
core.api_key_manager
¶
API key management with file watching and caching.
APIKeyFileHandler
¶
Bases: FileSystemEventHandler
File system event handler for API key files.
Initialize the handler.
Parameters:
-
manager(APIKeyManager) –The APIKeyManager instance to notify
-
file_path(Path) –Path to the API key file being watched
Source code in core/api_key_manager.py
on_modified
¶
Handle file modification events.
Parameters:
-
event(FileSystemEvent) –The file system event
Source code in core/api_key_manager.py
APIKeyManager
¶
Manages API keys from strings and files with automatic reloading.
Initialize the API key manager.
Source code in core/api_key_manager.py
load_keys
¶
Load API keys from a string or file.
Parameters:
-
source(str) –Either comma-separated API keys or a file path
-
source_id(str, default:'default') –Identifier for this key source (for caching)
Returns:
-
set[str]–Set of valid API keys
Raises:
-
ValueError–If the source appears to be a file path but doesn't exist
Source code in core/api_key_manager.py
reload_file
¶
Reload API keys from a file.
Parameters:
-
file_path(str) –Path to the file to reload
Source code in core/api_key_manager.py
get_cached_keys
¶
Get cached keys for a source.
Parameters:
-
source(str) –The source string (file path or keys)
Returns:
-
set[str] | None–Set of keys if cached, None otherwise
Source code in core/api_key_manager.py
validate_key
¶
Validate an API key against one or more sources.
Parameters:
-
api_key(str) –The API key to validate
-
*sources(str, default:()) –One or more sources (file paths or key strings)
Returns:
-
bool–True if the key is valid in any source, False otherwise
Source code in core/api_key_manager.py
shutdown
¶
Stop all file watchers.
get_api_key_manager
¶
Get the global API key manager instance.
Returns:
-
APIKeyManager–The APIKeyManager instance
Source code in core/api_key_manager.py
API Key Validator¶
core.api_key_validator
¶
API key configuration validation.
APIKeyValidationError
¶
Bases: Exception
Raised when API key configuration is invalid.
validate_api_key_source
¶
Validate an API key source (string or file path).
Parameters:
-
source(str) –The API key source (comma-separated keys or file path)
-
source_name(str, default:'api_keys') –Name of the source for error messages
Returns:
-
dict–Dictionary with validation results:
-
dict–{ "valid": bool, "type": "file" | "string", "path": Optional[Path], "warnings": list[str], "errors": list[str]
-
dict–}
Raises:
-
APIKeyValidationError–If the source is invalid
Source code in core/api_key_validator.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
validate_settings_api_keys
¶
Validate API keys in settings file.
Parameters:
-
settings_path(str, default:'config/settings.json') –Path to settings.json file
Returns:
-
bool–True if valid, False otherwise
Source code in core/api_key_validator.py
validate_endpoints_api_keys
¶
Validate API keys in endpoints file.
Parameters:
-
endpoints_path(str, default:'config/endpoints.json') –Path to endpoints.json file
Returns:
-
bool–True if valid, False otherwise
Source code in core/api_key_validator.py
validate_all_api_keys
¶
validate_all_api_keys(
settings_path: str = "config/settings.json",
endpoints_path: str = "config/endpoints.json",
) -> bool
Validate all API key configurations.
Parameters:
-
settings_path(str, default:'config/settings.json') –Path to settings.json file
-
endpoints_path(str, default:'config/endpoints.json') –Path to endpoints.json file
Returns:
-
bool–True if all configurations are valid, False otherwise
Source code in core/api_key_validator.py
Caching¶
core.cache
¶
Caching utilities for endpoints.
SimpleCache
¶
Simple in-memory cache with TTL.
Initialize cache.
Source code in core/cache.py
get
¶
Get value from cache.
Parameters:
-
key(str) –Cache key
Returns:
-
Any | None–Cached value or None if not found or expired
Source code in core/cache.py
set
¶
Set value in cache.
Parameters:
-
key(str) –Cache key
-
value(Any) –Value to cache
-
ttl(int, default:60) –Time to live in seconds
cache_response
¶
Decorator to cache endpoint responses.
Parameters:
-
ttl(int, default:60) –Time to live in seconds
-
key_func(Callable | None, default:None) –Optional function to generate cache key from request
Returns:
-
–
Decorated function
Source code in core/cache.py
add_cache_headers
¶
Add cache headers to response.
Parameters:
-
response(Response) –FastAPI response object
-
ttl(int, default:60) –Time to live in seconds
-
etag(str | None, default:None) –Optional ETag value
Source code in core/cache.py
Dependencies¶
core.dependencies
¶
Shared dependencies for dependency injection.
HTTPClientDependency
¶
Dependency class for HTTP client with connection pooling.
Initialize the HTTP client dependency.
Source code in core/dependencies.py
__call__
async
¶
Get or create the HTTP client.
Source code in core/dependencies.py
get_settings_cached
cached
¶
get_http_client
¶
Get an HTTP client instance.
Note: This creates a new client each time. For connection pooling, consider using a shared client instance managed by the application.
Returns:
-
AsyncClient–httpx.AsyncClient instance.
Source code in core/dependencies.py
Rate Limiting¶
core.rate_limiter
¶
Rate limiting middleware and utilities.
RateLimiter
¶
Simple in-memory rate limiter.
Note: State is per-process. When running multiple Gunicorn workers, each worker maintains its own rate limit counters, effectively multiplying the allowed rate by the number of workers. Use a shared store (e.g. Redis) if accurate cross-worker rate limiting is needed.
Initialize rate limiter.
Source code in core/rate_limiter.py
check_rate_limit
¶
Check if request is within rate limit.
Parameters:
-
identifier(str) –Unique identifier (IP address, API key, etc.)
-
limit(int) –Maximum number of requests allowed
-
window_seconds(int, default:60) –Time window in seconds (default: 60)
Returns:
-
tuple[bool, int, int]–Tuple of (is_allowed, remaining, reset_time)
Source code in core/rate_limiter.py
RateLimitMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware for rate limiting.
dispatch
async
¶
Apply rate limiting to requests.
Source code in core/rate_limiter.py
Request Validation¶
core.request_validation
¶
Request validation and sanitization utilities.
RequestValidationMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware for request validation and sanitization.
dispatch
async
¶
Validate and sanitize requests.
Source code in core/request_validation.py
Middleware¶
core.middleware
¶
Middleware for request/response processing.
RequestIDMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware to add request ID to requests and responses.
dispatch
async
¶
Process request and add request ID.
Source code in core/middleware.py
LoggingMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware for request/response logging.
dispatch
async
¶
Log request and response.
Source code in core/middleware.py
SecurityHeadersMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware to add security headers to responses.
dispatch
async
¶
Add security headers to response.
Source code in core/middleware.py
configure_cors
¶
Configure CORS middleware for the application.
Parameters:
-
app(Starlette) –FastAPI application instance
-
allowed_origins(list[str] | None, default:None) –List of allowed origins. If None, allows all origins.
Source code in core/middleware.py
Router Factory¶
core.router_factory
¶
Dynamic router factory for configurable endpoints.
DynamicRouter
¶
Dynamic router for configurable endpoints.
Initialize dynamic router.
Parameters:
-
app(FastAPI) –FastAPI application instance
Source code in core/router_factory.py
register_endpoint
¶
Register a single endpoint from configuration.
Parameters:
-
config(EndpointConfig) –Endpoint configuration
Source code in core/router_factory.py
load_and_register
¶
Load configuration and register all endpoints.
Parameters:
-
config_path(str, default:'config/endpoints.json') –Path to endpoints configuration file
Source code in core/router_factory.py
Metrics¶
core.metrics
¶
Metrics collection for monitoring.
EndpointMetrics
dataclass
¶
MetricsCollector
¶
Collects metrics for the API.
Note: State is per-process. When running multiple Gunicorn workers, each worker maintains its own metrics. Use a shared store (e.g. Redis or Prometheus) if aggregated cross-worker metrics are needed.
Initialize metrics collector.
Source code in core/metrics.py
record_request
¶
Record a request metric.
Parameters:
-
path(str) –Request path
-
method(str) –HTTP method
-
status_code(int) –Response status code
-
duration(float) –Request duration in seconds
Source code in core/metrics.py
get_metrics
¶
Get all collected metrics.
Returns:
-
dict–Dictionary with metrics data
Source code in core/metrics.py
MetricsMiddleware
¶
Bases: BaseHTTPMiddleware
Middleware for collecting metrics.
dispatch
async
¶
Collect metrics for requests.
Source code in core/metrics.py
Logging¶
core.logging_config
¶
Logging configuration for the application.
setup_logging
¶
setup_logging(
level: str = "INFO",
log_file: Path | None = None,
log_format: str | None = None,
) -> None
Configure application logging.
Parameters:
-
level(str, default:'INFO') –Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
-
log_file(Path | None, default:None) –Optional path to log file
-
log_format(str | None, default:None) –Optional custom log format