A comprehensive Python SDK for backend systems development at midil.io. This library provides a rich set of tools for building modern, scalable backend applications with support for authentication, event handling, HTTP clients, and JSON:API compliance.
- JWT Authorization: Comprehensive JWT token verification and validation
- AWS Cognito Integration: Ready-to-use Cognito client credentials flow and JWT authorizer
- Pluggable Auth Providers: Abstract interfaces for custom authentication implementations
- FastAPI Middleware: Built-in authentication middleware for FastAPI applications
- Event Dispatching: Abstract event dispatcher with polling and AWS integrations
- SQS Consumer: AWS SQS message consumption with automatic retry and context handling
- Event Scheduling: AWS EventBridge integration and periodic task scheduling
- Event Context: Distributed tracing and context management for events
- Enhanced HTTP Client: HTTPX-based client with authentication integration
- Retry Logic: Configurable retry strategies with exponential backoff and jitter
- Transport Layer: Custom transport with comprehensive error handling
- Auth Integration: Seamless integration with authentication providers
- Document Creation: Full JSON:API compliant document creation and validation
- Resource Management: Type-safe resource objects with relationships
- Query Parameters: Parsing and validation of JSON:API query parameters (sort, include, pagination)
- Error Handling: Standardized JSON:API error document creation
- FastAPI Integration: Authentication middleware and JSON:API dependencies
- Type Safety: Full type hints throughout with Pydantic models
- Async Support: Native async/await support across all components
poetry add midil-kitpip install midil-kitThe library supports optional feature sets through extras:
# Web framework extensions (FastAPI)
poetry add midil-kit[fastapi]
# Authentication providers (JWT, Cognito)
poetry add midil-kit[auth]
# AWS event services (SQS, EventBridge)
poetry add midil-kit[event]
# AWS infrastructure (auth + event)
poetry add midil-kit[aws]
# All optional dependencies
poetry add midil-kit[all]from midil.auth.cognito import CognitoClientCredentialsAuthenticator, CognitoJWTAuthorizer
# Authentication client for outbound requests
auth_client = CognitoClientCredentialsAuthenticator(
client_id="your-client-id",
client_secret="your-client-secret",
cognito_domain="your-domain.auth.region.amazoncognito.com"
)
# Get access token
token = await auth_client.get_token()
headers = await auth_client.get_headers()
# JWT authorizer for inbound requests
authorizer = CognitoJWTAuthorizer(
user_pool_id="your-user-pool-id",
region="us-east-1"
)
# Verify incoming token
claims = await authorizer.verify("jwt-token")from midil.event.dispatchers.polling import PollingEventDispatcher
from midil.event.consumer.sqs import run_sqs_consumer
from midil.event.context import event_context
# Event dispatcher
dispatcher = PollingEventDispatcher()
# Register event handlers
@dispatcher.on("user.created")
async def handle_user_created(event: str, body: dict):
print(f"User created: {body['user_id']}")
# Start event processing
await dispatcher.start_event_processor()
# Send events
await dispatcher.notify("user.created", {"user_id": "123"})
# SQS consumer
await run_sqs_consumer(
queue_url="https://sqs.region.amazonaws.com/account/queue-name",
region_name="us-east-1"
)from midil.http_client import HttpClient
from midil.auth.cognito import CognitoClientCredentialsAuthenticator
from httpx import URL
# Create authenticated HTTP client
auth_client = CognitoClientCredentialsAuthenticator(...)
http_client = HttpClient(
auth_client=auth_client,
base_url=URL("https://api.example.com")
)
# Make authenticated requests
response = await http_client.send_request(
method="POST",
url="/users",
data={"name": "John Doe"}
)from midil.jsonapi import Document, ResourceObject, ErrorObject
# Create a resource document
resource = ResourceObject(
id="1",
type="articles",
attributes={"title": "JSON:API with Midil Kit", "content": "..."}
)
document = Document(data=resource)
# Create error documents
error = ErrorObject(
status="422",
title="Validation Error",
detail="Title is required"
)
error_document = Document(errors=[error])from fastapi import FastAPI, Depends
from midil.midilapi.fastapi.middleware.auth_middleware import CognitoAuthMiddleware
from midil.midilapi.fastapi.dependencies.jsonapi import parse_sort, parse_include
app = FastAPI()
# Add authentication middleware
app.add_middleware(CognitoAuthMiddleware)
# JSON:API query parameter parsing
@app.get("/articles")
async def list_articles(
sort=Depends(parse_sort),
include=Depends(parse_include)
):
return {"data": [], "meta": {"sort": sort, "include": include}}
# Access authenticated user
def get_auth(request):
return request.state.auth
@app.get("/me")
async def get_current_user(auth=Depends(get_auth)):
return {"user_id": auth.claims.sub}AuthNProvider: Abstract authentication provider for outbound requestsAuthZProvider: Abstract authorization provider for inbound token verificationAuthNToken: Token model with expiration handlingAuthZTokenClaims: Token claims model
CognitoClientCredentialsAuthenticator: OAuth2 client credentials flowCognitoJWTAuthorizer: JWT token verification for Cognito
AbstractEventDispatcher: Base event dispatcher with memory queuePollingEventDispatcher: In-memory event dispatcher with observer pattern
SQSEventConsumer: AWS SQS message consumer with retry logic
AWSEventBridgeClient: EventBridge integration for scheduled eventsPeriodicTask: Periodic task execution with customizable strategies
EventContext: Event tracing and context managementevent_context(): Async context manager for event scoping
HttpClient: Enhanced HTTP client with auth integrationMidilAsyncClient: Custom HTTPX client with retry transport
RetryTransport: Configurable retry transport layerDefaultRetryStrategy: Standard retry strategy implementationExponentialBackoffWithJitter: Backoff strategy with jitter
Document: Main document containerResourceObject: Resource representation with attributes and relationshipsErrorObject: Error representationQueryParams: Query parameter parsing and validation
Sort,Include,PaginationParams: Query parameter models
BaseAuthMiddleware: Base authentication middlewareCognitoAuthMiddleware: Cognito-specific middlewareAuthContext: Request authentication contextparse_sort(),parse_include(): JSON:API query parameter dependencies
- Python 3.12+
- Poetry for dependency management
- Clone the repository:
git clone <repository-url>
cd midil-kit- Install dependencies:
make install- Install pre-commit hooks:
make pre-commit-install# Run tests
make test
# Run tests with coverage
make test-cov
# Lint code
make lint
# Format code
make format
# Type checking
make type-check
# Run all checks
make check
# Clean build artifacts
make clean
# Build package
make buildThe project uses towncrier for changelog management:
# Create a changelog entry
make changelog-draft
# Preview changelog changes
make changelog-preview
# Update changelog
make changelog
# Prepare a new release
make release# Run all tests
poetry run pytest
# Run with coverage
poetry run pytest --cov=midil --cov-report=html
# Run specific test file
poetry run pytest tests/auth/test_cognito.pyThe project enforces code quality through:
- Black: Code formatting
- Ruff: Fast Python linter
- MyPy: Static type checking
- Pre-commit hooks: Automated quality checks
Midil Kit follows a modular architecture:
midil/
βββ auth/ # Authentication & authorization
βββ event/ # Event system & messaging
βββ http/ # HTTP client & retry logic
βββ jsonapi/ # JSON:API compliance
βββ extensions/ # Framework integrations
βββ fastapi/ # FastAPI-specific extensions
- Type Safety: Comprehensive type hints using Pydantic models
- Async First: Native async/await support throughout
- Pluggable: Abstract interfaces for custom implementations
- Framework Agnostic: Core functionality independent of web frameworks
- AWS Native: First-class support for AWS services
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for new functionality
- Ensure all tests pass (
make check) - Create a changelog entry (
make changelog-draft) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project follows Conventional Commits:
<type>(<scope>): <description>
[optional body]
[optional footer(s)]
Types:
feat: A new featurefix: A bug fixdocs: Documentation only changesstyle: Changes that do not affect the meaning of the coderefactor: A code change that neither fixes a bug nor adds a featuretest: Adding missing tests or correcting existing testschore: Changes to the build process or auxiliary tools
Scopes:
auth: Authentication & authorizationevent: Event systemhttp: HTTP clientjsonapi: JSON:API functionalityextensions: Framework extensionsdocs: Documentationci: Continuous integration
Examples:
feat(auth): add support for refresh tokens
fix(event): resolve memory leak in event dispatcher
docs: update installation instructions
test(jsonapi): add tests for error document creation
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
See CHANGELOG.md for a detailed history of changes.
- v3.0.0 - Breaking changes with improved naming conventions and PATCH/POST resource compliance
- v2.1.0 - Infrastructure packages, FastAPI extensions, and improved interfaces
- v2.0.0 - Major architectural improvements with auth, http, and event modules
- π§ Email: [email protected]
- π Website: midil.io
- π Documentation: [Coming Soon]
Built with β€οΈ by the Midil.io team for the Python backend development community.