From ddd63519e50916195c4c0d3f56d7a0abb451bfe8 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Sat, 28 Jun 2025 02:23:56 +0000 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20Add=20comprehensive=20README=20d?= =?UTF-8?q?ocumentation=20for=20core=20modules=20and=20scripts?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add README for dependencies module explaining dependency injection system - Add README for middleware module covering available middleware components - Add README for openapi module documenting schema generation utilities - Add README for security module covering authentication implementations - Add README for scripts directory documenting build and development tools Improves developer experience by providing clear documentation for previously undocumented parts of the codebase. Co-Authored-By: The Coding Gopher --- fastapi/dependencies/README.md | 42 ++++++++++ fastapi/middleware/README.md | 84 ++++++++++++++++++++ fastapi/openapi/README.md | 78 +++++++++++++++++++ fastapi/security/README.md | 119 ++++++++++++++++++++++++++++ scripts/README.md | 138 +++++++++++++++++++++++++++++++++ 5 files changed, 461 insertions(+) create mode 100644 fastapi/dependencies/README.md create mode 100644 fastapi/middleware/README.md create mode 100644 fastapi/openapi/README.md create mode 100644 fastapi/security/README.md create mode 100644 scripts/README.md diff --git a/fastapi/dependencies/README.md b/fastapi/dependencies/README.md new file mode 100644 index 0000000000000..9373d778a7acd --- /dev/null +++ b/fastapi/dependencies/README.md @@ -0,0 +1,42 @@ +# FastAPI Dependencies + +This module contains the core dependency injection system for FastAPI applications. + +## Overview + +FastAPI's dependency injection system allows you to declare dependencies that will be automatically resolved and injected into your path operation functions. This provides a clean way to share code, database connections, enforce security, and more. + +## Module Contents + +### `models.py` +Contains the core data models and classes used by the dependency injection system, including dependency resolution logic and parameter handling. + +### `utils.py` +Utility functions for dependency resolution, parameter extraction, and dependency graph management. + +## Basic Usage + +```python +from fastapi import FastAPI, Depends + +app = FastAPI() + +def common_parameters(q: str = None, skip: int = 0, limit: int = 100): + return {"q": q, "skip": skip, "limit": limit} + +@app.get("/items/") +async def read_items(commons: dict = Depends(common_parameters)): + return commons +``` + +## Key Features + +- **Automatic Resolution**: Dependencies are automatically resolved based on type hints +- **Nested Dependencies**: Dependencies can have their own dependencies +- **Caching**: Dependencies can be cached to avoid repeated execution +- **Security Integration**: Works seamlessly with FastAPI's security utilities +- **Database Integration**: Perfect for database session management + +## Learn More + +For comprehensive tutorials and advanced usage patterns, see the [FastAPI Dependencies documentation](https://fastapi.tiangolo.com/tutorial/dependencies/). diff --git a/fastapi/middleware/README.md b/fastapi/middleware/README.md new file mode 100644 index 0000000000000..f6f7228f7ca1f --- /dev/null +++ b/fastapi/middleware/README.md @@ -0,0 +1,84 @@ +# FastAPI Middleware + +This module provides middleware components for FastAPI applications, built on top of Starlette's middleware system. + +## Overview + +Middleware in FastAPI allows you to add functionality that runs before and after each request. This module includes commonly used middleware for CORS, compression, security, and more. + +## Available Middleware + +### `cors.py` +Cross-Origin Resource Sharing (CORS) middleware for handling cross-origin requests. + +```python +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +app = FastAPI() + +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) +``` + +### `gzip.py` +GZip compression middleware to automatically compress responses. + +```python +from fastapi.middleware.gzip import GZipMiddleware + +app.add_middleware(GZipMiddleware, minimum_size=1000) +``` + +### `httpsredirect.py` +HTTPS redirect middleware to automatically redirect HTTP requests to HTTPS. + +```python +from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware + +app.add_middleware(HTTPSRedirectMiddleware) +``` + +### `trustedhost.py` +Trusted host middleware to validate the Host header against a list of allowed hosts. + +```python +from fastapi.middleware.trustedhost import TrustedHostMiddleware + +app.add_middleware( + TrustedHostMiddleware, + allowed_hosts=["example.com", "*.example.com"] +) +``` + +### `wsgi.py` +WSGI middleware for mounting WSGI applications within FastAPI. + +```python +from fastapi.middleware.wsgi import WSGIMiddleware +from flask import Flask + +flask_app = Flask(__name__) +app.mount("/flask", WSGIMiddleware(flask_app)) +``` + +## Usage Pattern + +All middleware follows the same pattern: + +```python +from fastapi import FastAPI +from fastapi.middleware.{middleware_name} import {MiddlewareClass} + +app = FastAPI() +app.add_middleware(MiddlewareClass, **options) +``` + +## Learn More + +For detailed configuration options and advanced usage, see the [FastAPI Middleware documentation](https://fastapi.tiangolo.com/tutorial/middleware/) and [Starlette Middleware documentation](https://www.starlette.io/middleware/). diff --git a/fastapi/openapi/README.md b/fastapi/openapi/README.md new file mode 100644 index 0000000000000..dc146f7a079d2 --- /dev/null +++ b/fastapi/openapi/README.md @@ -0,0 +1,78 @@ +# FastAPI OpenAPI + +This module handles OpenAPI schema generation and documentation for FastAPI applications. + +## Overview + +FastAPI automatically generates OpenAPI schemas for your API, which power the interactive documentation (Swagger UI and ReDoc). This module contains the core functionality for schema generation, customization, and documentation rendering. + +## Module Contents + +### `constants.py` +Contains constants used throughout the OpenAPI schema generation process, including HTTP status codes, content types, and schema definitions. + +### `docs.py` +Handles the generation and serving of interactive API documentation (Swagger UI and ReDoc interfaces). + +### `models.py` +Pydantic models that represent OpenAPI schema components, including operations, parameters, responses, and security definitions. + +### `utils.py` +Utility functions for schema generation, including parameter extraction, response modeling, and schema merging. + +## Basic Customization + +```python +from fastapi import FastAPI + +app = FastAPI( + title="My API", + description="A custom API with OpenAPI documentation", + version="1.0.0", + openapi_tags=[ + { + "name": "items", + "description": "Operations with items", + } + ] +) + +@app.get("/items/", tags=["items"]) +async def read_items(): + return [{"item_id": "Foo"}] +``` + +## Advanced Schema Customization + +```python +from fastapi.openapi.utils import get_openapi + +def custom_openapi(): + if app.openapi_schema: + return app.openapi_schema + openapi_schema = get_openapi( + title="Custom API", + version="2.5.0", + description="This is a very custom OpenAPI schema", + routes=app.routes, + ) + openapi_schema["info"]["x-logo"] = { + "url": "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" + } + app.openapi_schema = openapi_schema + return app.openapi_schema + +app.openapi = custom_openapi +``` + +## Key Features + +- **Automatic Schema Generation**: Schemas are generated from your Python type hints +- **Interactive Documentation**: Swagger UI and ReDoc interfaces are automatically available +- **Customizable**: Full control over OpenAPI schema generation and documentation +- **Standards Compliant**: Generates valid OpenAPI 3.0+ schemas +- **Security Integration**: Automatic security scheme documentation + +## Learn More + +For comprehensive guides on customizing OpenAPI schemas and documentation, see the [FastAPI OpenAPI documentation](https://fastapi.tiangolo.com/advanced/extending-openapi/). diff --git a/fastapi/security/README.md b/fastapi/security/README.md new file mode 100644 index 0000000000000..ee2ff536acf42 --- /dev/null +++ b/fastapi/security/README.md @@ -0,0 +1,119 @@ +# FastAPI Security + +This module provides security utilities and authentication implementations for FastAPI applications. + +## Overview + +FastAPI's security module offers a comprehensive set of tools for implementing authentication and authorization in your APIs. It supports various authentication schemes including OAuth2, API keys, HTTP Basic/Bearer authentication, and more. + +## Security Components + +### `oauth2.py` +OAuth2 authentication flows including Authorization Code, Client Credentials, and Password flows. + +```python +from fastapi import FastAPI, Depends +from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm + +app = FastAPI() +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") + +@app.post("/token") +async def login(form_data: OAuth2PasswordRequestForm = Depends()): + # Authenticate user and return token + return {"access_token": "fake-token", "token_type": "bearer"} + +@app.get("/users/me") +async def read_users_me(token: str = Depends(oauth2_scheme)): + return {"token": token} +``` + +### `api_key.py` +API key authentication for header, query parameter, or cookie-based authentication. + +```python +from fastapi.security import APIKeyHeader + +api_key_header = APIKeyHeader(name="X-API-Key") + +@app.get("/protected") +async def protected_route(api_key: str = Depends(api_key_header)): + return {"message": "Access granted"} +``` + +### `http.py` +HTTP authentication schemes including Basic and Bearer authentication. + +```python +from fastapi.security import HTTPBasic, HTTPBearer + +security_basic = HTTPBasic() +security_bearer = HTTPBearer() + +@app.get("/basic") +async def basic_auth(credentials: HTTPBasicCredentials = Depends(security_basic)): + return {"username": credentials.username} +``` + +### `open_id_connect_url.py` +OpenID Connect authentication support for integration with identity providers. + +```python +from fastapi.security import OpenIdConnect + +openid_connect = OpenIdConnect(openIdConnectUrl="/.well-known/openid_configuration") +``` + +### `base.py` +Base classes and utilities for implementing custom security schemes. + +### `utils.py` +Utility functions for security operations including token validation, password hashing, and security scheme helpers. + +## Common Patterns + +### JWT Token Authentication +```python +from fastapi import FastAPI, Depends, HTTPException, status +from fastapi.security import HTTPBearer +import jwt + +security = HTTPBearer() + +def verify_token(token: str = Depends(security)): + try: + payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) + return payload + except jwt.PyJWTError: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid token" + ) +``` + +### Role-Based Access Control +```python +def require_role(required_role: str): + def role_checker(current_user: dict = Depends(get_current_user)): + if current_user.get("role") != required_role: + raise HTTPException(status_code=403, detail="Insufficient permissions") + return current_user + return role_checker + +@app.get("/admin") +async def admin_only(user: dict = Depends(require_role("admin"))): + return {"message": "Admin access granted"} +``` + +## Security Best Practices + +- Always use HTTPS in production +- Implement proper token expiration and refresh mechanisms +- Use strong, randomly generated secrets for signing tokens +- Validate and sanitize all input data +- Implement rate limiting to prevent abuse +- Log security events for monitoring + +## Learn More + +For detailed tutorials and advanced security patterns, see the [FastAPI Security documentation](https://fastapi.tiangolo.com/tutorial/security/). diff --git a/scripts/README.md b/scripts/README.md new file mode 100644 index 0000000000000..3ecf789c670e4 --- /dev/null +++ b/scripts/README.md @@ -0,0 +1,138 @@ +# FastAPI Development Scripts + +This directory contains various scripts for development, documentation building, translation management, and project maintenance. + +## Overview + +These scripts automate common development tasks for the FastAPI project, including documentation generation, translation workflows, contributor management, and code quality checks. + +## Key Scripts + +### `docs.py` +Comprehensive documentation build system for multi-language documentation. + +**Key Features:** +- Build documentation for multiple languages +- Generate README from main documentation +- Manage translation workflows +- Serve documentation locally with live reload +- Verify documentation consistency + +**Common Commands:** +```bash +# Build all language documentation +python scripts/docs.py build-all + +# Serve documentation locally +python scripts/docs.py live en + +# Generate README from docs +python scripts/docs.py generate-readme + +# Verify documentation consistency +python scripts/docs.py verify-docs +``` + +### `contributors.py` +Automated contributor and translator tracking system. + +**Features:** +- Fetches contributor data from GitHub API +- Tracks pull request authors and reviewers +- Generates contributor statistics +- Updates contributor data files automatically +- Creates automated PRs for contributor updates + +**Usage:** +Requires GitHub token and repository configuration. Typically run in CI/CD pipelines. + +### `translate.py` +AI-powered translation system for documentation. + +**Features:** +- Translates documentation using AI (GPT-4) +- Maintains translation consistency +- Handles technical terms appropriately +- Preserves code snippets and formatting +- Updates existing translations + +**Usage:** +```bash +# Translate a specific file +python scripts/translate.py --lang es --path docs/en/docs/tutorial/index.md + +# Translate all missing files for a language +python scripts/translate.py --lang es +``` + +### Shell Scripts + +#### `format.sh` +Code formatting using Ruff formatter. + +#### `lint.sh` +Code linting and style checking. + +#### `test.sh` +Run the test suite. + +#### `test-cov-html.sh` +Run tests with HTML coverage report. + +### Other Utilities + +#### `people.py` +Manages FastAPI people and community data. + +#### `sponsors.py` +Handles sponsor information and display. + +#### `topic_repos.py` +Manages topic-related repository information. + +#### `label_approved.py` +Automated labeling for approved pull requests. + +#### `deploy_docs_status.py` +Manages documentation deployment status. + +#### `notify_translations.py` +Notification system for translation updates. + +#### `mkdocs_hooks.py` +Custom hooks for MkDocs documentation building. + +#### `playwright/` +End-to-end testing utilities using Playwright. + +## Prerequisites + +Most scripts require: +- Python 3.8+ +- Required dependencies (install with `pip install -r requirements-docs.txt`) +- For some scripts: GitHub token, OpenAI API key, or other credentials + +## Development Workflow + +1. **Documentation Changes**: Use `docs.py live` for local development +2. **Code Changes**: Run `lint.sh` and `test.sh` before committing +3. **Translation Updates**: Use `translate.py` for new translations +4. **Release Preparation**: Run `docs.py verify-docs` to ensure consistency + +## CI/CD Integration + +Many of these scripts are integrated into GitHub Actions workflows for: +- Automated testing and linting +- Documentation building and deployment +- Translation management +- Contributor tracking +- Release automation + +## Learn More + +For specific script usage and configuration options, run: +```bash +python scripts/{script_name}.py --help +``` + +Or refer to the individual script files for detailed documentation and examples.