Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions fastapi/dependencies/README.md
Original file line number Diff line number Diff line change
@@ -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/).
84 changes: 84 additions & 0 deletions fastapi/middleware/README.md
Original file line number Diff line number Diff line change
@@ -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/).
78 changes: 78 additions & 0 deletions fastapi/openapi/README.md
Original file line number Diff line number Diff line change
@@ -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/).
119 changes: 119 additions & 0 deletions fastapi/security/README.md
Original file line number Diff line number Diff line change
@@ -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/).
Loading