### Quick Start: Basic WellAPI Application Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md A minimal WellAPI application setup in `main.py` with a health check endpoint. It initializes `WellApi` with basic configuration and defines a GET route using `@app.get`. ```python from wellapi import RequestAPIGateway, WellApi app = WellApi( title="My API", version="1.0.0", debug=True, servers=[{"url": "http://localhost:8000", "description": "Local"}], ) @app.get("/health") def health(request: RequestAPIGateway): return {"ok": True, "method": request.raw_event.httpMethod} ``` -------------------------------- ### Basic WellAPI Application Setup Source: https://github.com/romayuhym/wellapi/blob/main/README.md A minimal example of a WellAPI application. It initializes the WellApi instance and defines a simple GET endpoint. ```python from wellapi import WellApi app = WellApi(title="My API", version="1.0.0") @app.get("/hello") def hello(): return {"message": "Hello, World!"} ``` -------------------------------- ### Minimal WellAPI Project Setup Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Demonstrates the basic file structure for a WellAPI project. `main.py` initializes the WellApi application, and handlers in the `handlers/` directory register routes. ```text project/ main.py handlers/ __init__.py users.py ``` -------------------------------- ### Install WellAPI with pip Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Installs the WellAPI package using pip. The minimal install includes the core library, while the recommended version adds support for local development, deployment, and telemetry. ```bash pip install wellapi pip install "wellapi[local,deploy,telemetry]" ``` -------------------------------- ### Install WellAPI Package Source: https://github.com/romayuhym/wellapi/blob/main/README.md Installs the base WellAPI package using pip. This is the fundamental step to begin using the framework. ```bash pip install wellapi ``` -------------------------------- ### Quick Start: User Routes with WellAPI Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Defines user-related routes in `handlers/users.py` using WellAPI decorators. It includes Pydantic models for request/response and demonstrates path parameters, query parameters, and header injection. ```python from typing import Annotated from pydantic import BaseModel, Field from main import app from wellapi import Header, Query class UserOut(BaseModel): id: int name: str class ListQuery(BaseModel): limit: int = Field(20, ge=1, le=100) offset: int = Field(0, ge=0) @app.get("/users/{user_id:int}") def get_user( user_id: int, trace_id: Annotated[str | None, Header(alias="x-trace-id")] = None, ) -> UserOut: return UserOut(id=user_id, name=f"user-{trace_id or 'n/a'}") @app.get("/users") def list_users(params: Annotated[ListQuery, Query()]): return {"limit": params.limit, "offset": params.offset} ``` -------------------------------- ### Install WellAPI with Optional Extras Source: https://github.com/romayuhym/wellapi/blob/main/README.md Installs WellAPI with additional features for local development, deployment, and telemetry. Choose extras based on your project needs. ```bash pip install "wellapi[local,deploy,telemetry]" ``` -------------------------------- ### Local Testing of WellAPI Application Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Provides an example of how to perform local testing of a WellAPI application without running a server. It utilizes the TestClient from wellapi.testclient to make requests to the application and assert responses. ```python from wellapi.testclient import TestClient from main import app import handlers.users # ensure routes are registered client = TestClient(app) response = client.get("/health") assert response.status_code == 200 ``` -------------------------------- ### WellAPI: Dependency Injection and Security Schemes Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Illustrates dependency injection and security schemes in WellAPI. It defines an `APIKeyHeader` and an `OAuth2PasswordBearer` scheme, and shows how to protect endpoints using `dependencies`. ```python from typing import Annotated from wellapi.exceptions import HTTPException from wellapi.params import Depends from wellapi.security import APIKeyHeader, OAuth2PasswordBearer api_key_scheme = APIKeyHeader(name="x-api-key") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def verify_token(token: Annotated[str, Depends(oauth2_scheme)]): if token != "fake-token": raise HTTPException(status_code=403, detail="Not authenticated") @app.post("/secure-api-key", dependencies=[Depends(api_key_scheme)]) def secure_api_key(): return {"ok": True} @app.post("/secure-bearer", dependencies=[Depends(verify_token)]) def secure_bearer(): return {"ok": True} ``` -------------------------------- ### GET /request-info Source: https://context7.com/romayuhym/wellapi/llms.txt Retrieves and returns information about the incoming request. ```APIDOC ## GET /request-info ### Description This endpoint demonstrates how to access and utilize the `RequestAPIGateway` object to retrieve details about the incoming HTTP request. ### Method GET ### Endpoint /request-info ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **method** (string) - The HTTP method of the request. - **path** (string) - The path of the request. - **query_params** (object) - A dictionary of query parameters. - **headers** (object) - A dictionary of request headers. - **source_ip** (string) - The source IP address of the request. #### Response Example ```json { "method": "GET", "path": "/request-info", "query_params": {}, "headers": { "user-agent": "curl/7.68.0", "accept": "*/*" }, "source_ip": "192.168.1.1" } ``` ``` -------------------------------- ### Define API Endpoints with Route Decorators (GET, POST, PUT, PATCH, DELETE) Source: https://context7.com/romayuhym/wellapi/llms.txt Illustrates how to define various HTTP API endpoints (GET, POST, PUT, PATCH, DELETE) using WellAPI's route decorators. It covers path parameters, request bodies, response models, status codes, and tags. ```python from typing import Annotated from pydantic import BaseModel, Field from wellapi import WellApi, Query, Header, Body app = WellApi(title="Users API", version="1.0.0") class User(BaseModel): id: int name: str email: str class CreateUserRequest(BaseModel): name: str = Field(..., min_length=1, max_length=100) email: str = Field(..., pattern=r"^[\w\.-]+@[\w\.-]+\.\w+$") class UpdateUserRequest(BaseModel): name: str | None = None email: str | None = None # GET endpoint with path parameter and response model @app.get("/users/{user_id:int}", tags=["users"]) def get_user(user_id: int) -> User: return User(id=user_id, name="John Doe", email="john@example.com") # curl https://api.example.com/users/123 # Output: {"id": 123, "name": "John Doe", "email": "john@example.com"} # POST endpoint with request body and custom status code @app.post("/users", status_code=201, tags=["users"]) def create_user(user: CreateUserRequest) -> User: return User(id=1, name=user.name, email=user.email) # curl -X POST https://api.example.com/users -H "Content-Type: application/json" -d '{"name": "Jane", "email": "jane@example.com"}' # Output: {"id": 1, "name": "Jane", "email": "jane@example.com"} # PUT endpoint for full resource update @app.put("/users/{user_id:int}", tags=["users"]) def update_user(user_id: int, user: CreateUserRequest) -> User: return User(id=user_id, name=user.name, email=user.email) # PATCH endpoint for partial update @app.patch("/users/{user_id:int}", tags=["users"]) def patch_user(user_id: int, user: UpdateUserRequest) -> User: return User(id=user_id, name=user.name or "Updated", email=user.email or "updated@example.com") # DELETE endpoint @app.delete("/users/{user_id:int}", status_code=204, tags=["users"]) def delete_user(user_id: int): return None # curl -X DELETE https://api.example.com/users/123 # Output: (empty body with 204 status) ``` -------------------------------- ### Route Decorators (GET, POST, PUT, PATCH, DELETE) Source: https://context7.com/romayuhym/wellapi/llms.txt Illustrates the usage of route decorators for defining various HTTP methods, including path parameters, request bodies, and response models. ```APIDOC ## Route Decorators (GET, POST, PUT, PATCH, DELETE) ### Description WellAPI provides decorators for standard HTTP methods to define API endpoints. These decorators support path parameters, request bodies, response models, status codes, and more. ### GET /users/{user_id:int} #### Description Retrieves a user by their integer ID. #### Method GET #### Endpoint /users/{user_id:int} #### Parameters ##### Path Parameters - **user_id** (int) - Required - The ID of the user to retrieve. ##### Query Parameters None ##### Request Body None ### Response #### Success Response (200) - **id** (int) - The user's ID. - **name** (string) - The user's name. - **email** (string) - The user's email address. #### Response Example ```json { "id": 123, "name": "John Doe", "email": "john@example.com" } ``` --- ### POST /users #### Description Creates a new user with the provided details. #### Method POST #### Endpoint /users #### Parameters ##### Path Parameters None ##### Query Parameters None ##### Request Body - **name** (string) - Required - The name of the user (1-100 characters). - **email** (string) - Required - The email address of the user (valid email format). ### Response #### Success Response (201) - **id** (int) - The ID of the newly created user. - **name** (string) - The name of the user. - **email** (string) - The email address of the user. #### Response Example ```json { "id": 1, "name": "Jane", "email": "jane@example.com" } ``` --- ### PUT /users/{user_id:int} #### Description Updates an existing user's information completely. #### Method PUT #### Endpoint /users/{user_id:int} #### Parameters ##### Path Parameters - **user_id** (int) - Required - The ID of the user to update. ##### Query Parameters None ##### Request Body - **name** (string) - Required - The updated name of the user (1-100 characters). - **email** (string) - Required - The updated email address of the user (valid email format). ### Response #### Success Response (200) - **id** (int) - The user's ID. - **name** (string) - The updated name of the user. - **email** (string) - The updated email address of the user. #### Response Example ```json { "id": 123, "name": "Updated Name", "email": "updated@example.com" } ``` --- ### PATCH /users/{user_id:int} #### Description Partially updates an existing user's information. #### Method PATCH #### Endpoint /users/{user_id:int} #### Parameters ##### Path Parameters - **user_id** (int) - Required - The ID of the user to partially update. ##### Query Parameters None ##### Request Body - **name** (string) - Optional - The new name for the user. - **email** (string) - Optional - The new email address for the user. ### Response #### Success Response (200) - **id** (int) - The user's ID. - **name** (string) - The updated name of the user. - **email** (string) - The updated email address of the user. #### Response Example ```json { "id": 123, "name": "Updated Name", "email": "updated@example.com" } ``` --- ### DELETE /users/{user_id:int} #### Description Deletes a user by their integer ID. #### Method DELETE #### Endpoint /users/{user_id:int} #### Parameters ##### Path Parameters - **user_id** (int) - Required - The ID of the user to delete. ##### Query Parameters None ##### Request Body None ### Response #### Success Response (204) No content is returned upon successful deletion. #### Response Example (Empty Body) ``` -------------------------------- ### GET /traced Source: https://context7.com/romayuhym/wellapi/llms.txt A simple traced endpoint demonstrating telemetry integration. ```APIDOC ## GET /traced ### Description This endpoint is configured with telemetry, allowing tracing of requests and responses. ### Method GET ### Endpoint /traced ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **traced** (boolean) - Indicates if the endpoint is traced. #### Response Example ```json { "traced": true } ``` ``` -------------------------------- ### AWS CDK Integration for WellAPI Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Demonstrates how to integrate WellAPI into an AWS CDK stack. The WellApiCDK construct simplifies the setup of an API Gateway and Lambda function for the WellAPI application, with options for CORS, caching, and logging. ```python from aws_cdk import Stack from constructs import Construct from wellapi.build.cdk import WellApiCDK class ApiStack(Stack): def __init__(self, scope: Construct, id_: str, **kwargs): super().__init__(scope, id_, **kwargs) WellApiCDK( self, "WellApi", app_srt="main:app", handlers_dir="handlers", cors=True, cache_enable=False, log_enable=True, ) ``` -------------------------------- ### Path Parameters with Type Converters in WellAPI Source: https://context7.com/romayuhym/wellapi/llms.txt Demonstrates how to define path parameters with automatic type conversion in WellAPI. Supports types like int, float, uuid, and path. Includes example usage with curl commands. ```python from uuid import UUID from wellapi import WellApi app = WellApi(title="API", version="1.0.0") @app.get("/users/{user_id:int}") def get_user_by_id(user_id: int): return {"user_id": user_id, "type": "integer"} # curl https://api.example.com/users/42 # Output: {"user_id": 42, "type": "integer"} @app.get("/products/{product_id:uuid}") def get_product(product_id: UUID): return {"product_id": str(product_id)} # curl https://api.example.com/products/550e8400-e29b-41d4-a716-446655440000 # Output: {"product_id": "550e8400-e29b-41d4-a716-446655440000"} @app.get("/files/{file_path:path}") def get_file(file_path: str): return {"path": file_path} # curl https://api.example.com/files/documents/reports/2024/q1.pdf # Output: {"path": "documents/reports/2024/q1.pdf"} ``` -------------------------------- ### WellAPI: Middleware and Exception Handling Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Demonstrates implementing custom middleware and exception handlers in WellAPI. The `log_middleware` adds a header to responses, and `validation_exception_handler` customizes error responses for validation failures. ```python from wellapi.exceptions import RequestValidationError from wellapi.models import RequestAPIGateway, ResponseAPIGateway @app.middleware() def log_middleware(request: RequestAPIGateway, next_call) -> ResponseAPIGateway: response = next_call(request) response.headers["x-powered-by"] = "wellapi" return response @app.exception_handler(RequestValidationError) def validation_exception_handler(request, exc): return ResponseAPIGateway({"detail": exc.errors()}, status_code=422) ``` -------------------------------- ### Integrate OpenTelemetry for Tracing and Metrics in Python Source: https://context7.com/romayuhym/wellapi/llms.txt WellAPI supports OpenTelemetry integration for distributed tracing and metrics. By installing the `wellapi[telemetry]` extra and configuring OpenTelemetry providers, you can enable advanced observability for your API. ```python from wellapi import WellApi, RequestAPIGateway, ResponseAPIGateway from wellapi.telemetry.telemetry import Telemetry # Requires: pip install "wellapi[telemetry]" from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter app = WellApi(title="Traced API", version="1.0.0") ``` -------------------------------- ### GET /custom-response Source: https://context7.com/romayuhym/wellapi/llms.txt Returns a custom response with specified status code, headers, and content. ```APIDOC ## GET /custom-response ### Description This endpoint demonstrates how to construct and return a custom `ResponseAPIGateway` object, allowing full control over the HTTP response, including status code, headers, and body. ### Method GET ### Endpoint /custom-response ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **custom** (string) - A custom field within the response body. #### Response Example ```json { "custom": "response" } ``` **Note:** The response will also include the custom headers `x-custom-header: value` and `cache-control: max-age=3600`. ``` -------------------------------- ### WellAPI: SQS Handlers and Scheduled Jobs Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Shows how to define SQS message handlers and scheduled jobs using WellAPI decorators. `@app.sqs` processes messages from a queue, and `@app.job` runs a function on a schedule, demonstrating dependency injection for a database session. ```python from typing import Annotated from pydantic import BaseModel from wellapi.params import Depends class QueueEvent(BaseModel): name: str age: int @app.sqs("users-queue", batch_size=10) def process_users(events: list[QueueEvent]): for event in events: print(event.name) def db_session(): return "db-session" @app.job("rate(5 minutes)", name="sync_users") def sync_users(db: Annotated[str, Depends(db_session)]): print(db) ``` -------------------------------- ### Generate OpenAPI Specification with WellAPI CLI Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Generates an OpenAPI specification file for the WellAPI application. It requires the application entry point and handlers directory. Optional arguments include enabling CORS and specifying an IAM role name for API Gateway. ```bash wellapi openapi main:app handlers --output openapi.json ``` ```bash wellapi openapi main:app handlers --output openapi.json --cors true --role_name WellApiRole ``` -------------------------------- ### WellAPI: Handling Request Body with Pydantic Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Demonstrates how to handle complex JSON request bodies in WellAPI using Pydantic models. The `CreateUser` model defines the expected structure, and the `create_user` function receives it as an argument. ```python from pydantic import BaseModel class CreateUser(BaseModel): name: str age: int @app.post("/users", status_code=201) def create_user(item: CreateUser): return {"id": 1, **item.model_dump()} ``` -------------------------------- ### API Key Header Authentication in WellAPI Source: https://context7.com/romayuhym/wellapi/llms.txt Implements API key authentication using `APIKeyHeader` in WellAPI. Automatically handles missing or invalid keys with 403 errors. Includes examples for protected and admin endpoints. ```python from typing import Annotated from wellapi import WellApi, APIKeyHeader from wellapi.params import Depends from wellapi.exceptions import HTTPException app = WellApi(title="Secure API", version="1.0.0") api_key_scheme = APIKeyHeader(name="x-api-key", description="API Key for authentication") def verify_api_key(api_key: Annotated[str, Depends(api_key_scheme)]): valid_keys = {"secret-key-123", "admin-key-456"} if api_key not in valid_keys: raise HTTPException(status_code=403, detail="Invalid API key") return api_key @app.get("/protected", dependencies=[Depends(api_key_scheme)]) def protected_endpoint(): return {"message": "Access granted"} # curl https://api.example.com/protected -H "x-api-key: secret-key-123" # Output: {"message": "Access granted"} # curl https://api.example.com/protected # Output: {"detail": "Not authenticated"} (403 status) @app.get("/admin") def admin_endpoint(key: Annotated[str, Depends(verify_api_key)]): return {"message": "Admin access", "key_used": key} ``` -------------------------------- ### OAuth2 Password Bearer Authentication in WellAPI Source: https://context7.com/romayuhym/wellapi/llms.txt Shows how to implement OAuth2 Bearer token authentication using `OAuth2PasswordBearer` in WellAPI. Handles token validation and user retrieval. Includes examples for authenticated endpoints. ```python from typing import Annotated from wellapi import WellApi, OAuth2PasswordBearer from wellapi.params import Depends from wellapi.exceptions import HTTPException app = WellApi(title="OAuth API", version="1.0.0") oauth2_scheme = OAuth2PasswordBearer( tokenUrl="/auth/token", scopes={"read": "Read access", "write": "Write access"} ) def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]): # In production, validate JWT token here if token == "valid-token": return {"user_id": 1, "username": "john", "scopes": ["read", "write"]} raise HTTPException(status_code=401, detail="Invalid token") @app.get("/me") def get_profile(user: Annotated[dict, Depends(get_current_user)]): return {"user": user} # curl https://api.example.com/me -H "Authorization: Bearer valid-token" # Output: {"user": {"user_id": 1, "username": "john", "scopes": ["read", "write"]}} # curl https://api.example.com/me # Output: {"detail": "Not authenticated"} (401 status with WWW-Authenticate: Bearer header) ``` -------------------------------- ### Python Middleware for Request/Response Interception in WellAPI Source: https://context7.com/romayuhym/wellapi/llms.txt Demonstrates how to create middleware functions in Python using WellAPI to intercept requests and responses. These middlewares can be used for cross-cutting concerns like logging, timing, and header manipulation. The example shows a timing middleware and a CORS middleware. ```python from wellapi import WellApi, RequestAPIGateway, ResponseAPIGateway import time app = WellApi(title="API", version="1.0.0") @app.middleware() def timing_middleware(request: RequestAPIGateway, next_call) -> ResponseAPIGateway: start_time = time.time() response = next_call(request) duration = time.time() - start_time response.headers["x-response-time"] = f"{duration:.3f}s" return response @app.middleware() def cors_middleware(request: RequestAPIGateway, next_call) -> ResponseAPIGateway: response = next_call(request) response.headers["access-control-allow-origin"] = "*" response.headers["x-powered-by"] = "WellAPI" return response @app.get("/data") def get_data(): return {"data": "Hello World"} # curl https://api.example.com/data -v # Response headers include: x-response-time: 0.001s, access-control-allow-origin: *, x-powered-by: WellAPI ``` -------------------------------- ### Creating a WellAPI Application Source: https://context7.com/romayuhym/wellapi/llms.txt Demonstrates how to initialize a WellAPI application with configuration options and define a simple health check endpoint. ```APIDOC ## Creating a WellAPI Application ### Description This section shows how to create a `WellApi` application instance and define a basic GET endpoint for health checks. ### Method GET ### Endpoint /health ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from wellapi import WellApi app = WellApi( title="My Service API", version="1.0.0", description="A sample REST API built with WellAPI", servers=[{"url": "https://api.example.com", "description": "Production"}], debug=True, memory_size=256, timeout=30, use_snap_start=True, ) @app.get("/health") def health_check(): return {"status": "healthy", "version": "1.0.0"} ``` ### Response #### Success Response (200) - **status** (string) - The health status of the service. - **version** (string) - The version of the service. #### Response Example ```json { "status": "healthy", "version": "1.0.0" } ``` ``` -------------------------------- ### CLI: Build Deployment Artifacts Source: https://context7.com/romayuhym/wellapi/llms.txt Commands to package application code and dependencies into zip files for Lambda deployment. ```APIDOC ## CLI: Build Deployment Artifacts ### Description The `wellapi build` command packages application code and dependencies into zip files for Lambda deployment. ### Usage ```bash # Package application code (excluding dependencies) wellapi build app app.zip # Package dependencies as Lambda layer wellapi build dep dependencies.zip # Typical deployment workflow wellapi build app app.zip && wellapi build dep deps.zip # Upload app.zip to Lambda function # Upload deps.zip as Lambda layer ``` ``` -------------------------------- ### Create WellAPI Application Source: https://context7.com/romayuhym/wellapi/llms.txt Demonstrates the creation of a WellAPI application instance, configuring essential parameters like title, version, description, and AWS Lambda defaults. It also shows a basic health check endpoint. ```python from wellapi import WellApi app = WellApi( title="My Service API", version="1.0.0", description="A sample REST API built with WellAPI", servers=[{"url": "https://api.example.com", "description": "Production"}], debug=True, memory_size=256, timeout=30, use_snap_start=True, ) @app.get("/health") def health_check(): return {"status": "healthy", "version": "1.0.0"} # Expected output: {"status": "healthy", "version": "1.0.0"} ``` -------------------------------- ### Build Deployment Artifacts Source: https://github.com/romayuhym/wellapi/blob/main/README.md Creates zip archives for the application code and its dependencies, ready for deployment to AWS Lambda. ```bash wellapi build app app.zip wellapi build dep deps.zip ``` -------------------------------- ### Build Deployment Artifacts using CLI Source: https://context7.com/romayuhym/wellapi/llms.txt Packages application code and dependencies into zip files for Lambda deployment using the `wellapi build` command. It can package application code separately from dependencies, allowing dependencies to be deployed as a Lambda layer. ```bash # Package application code (excluding dependencies) wellapi build app app.zip # Package dependencies as Lambda layer wellapi build dep dependencies.zip # Typical deployment workflow wellapi build app app.zip && wellapi build dep deps.zip # Upload app.zip to Lambda function # Upload deps.zip as Lambda layer ``` -------------------------------- ### Configure OpenTelemetry Tracer and Meter Providers Source: https://context7.com/romayuhym/wellapi/llms.txt Sets up OpenTelemetry for tracing and metrics. It configures a TracerProvider with a BatchSpanProcessor and OTLPSpanExporter, and a MeterProvider. Telemetry is then initialized with these providers and custom request/response hooks for adding attributes like user agent and status code. ```python from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.trace.export import BatchSpanProcessor from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter from wellapi import app, RequestAPIGateway, ResponseAPIGateway, Telemetry tracer_provider = TracerProvider() tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter())) meter_provider = MeterProvider() aulemetry = Telemetry(tracer_provider=tracer_provider, meter_provider=meter_provider) def request_hook(span, request: RequestAPIGateway): span.set_attribute("http.user_agent", request.headers.get("user-agent", "")) def response_hook(span, response: ResponseAPIGateway | None): if response: span.set_attribute("http.status_code", response.statusCode) app.use_telemetry(telemetry, request_hook=request_hook, response_hook=response_hook) @app.get("/traced") def traced_endpoint(): return {"traced": True} ``` -------------------------------- ### Dependency Injection with Depends Source: https://context7.com/romayuhym/wellapi/llms.txt Illustrates how to use the `Depends` class for dependency injection, allowing for reusable logic like database connections, authentication, and shared services. ```APIDOC ## GET /users ### Description Lists users and demonstrates dependency injection for repository and settings. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **users** (array) - A list of user objects. - **repository** (object) - Information about the user repository. - **debug_mode** (boolean) - Indicates if debug mode is enabled. #### Response Example ```json { "users": [ { "id": 1, "name": "Alice" } ], "repository": { "db": { "connection": "postgres://localhost/mydb" }, "table": "users" }, "debug_mode": true } ``` ``` -------------------------------- ### Query and Header Parameters Source: https://context7.com/romayuhym/wellapi/llms.txt Explains how to use `Query` and `Header` annotations to extract and validate query string parameters and HTTP headers. ```APIDOC ## Query and Header Parameters ### Description This section demonstrates how to define query string parameters and HTTP headers using `Query` and `Header` annotations for data extraction and validation. ### GET /items #### Description Retrieves a list of items with pagination and optional sorting. It also accepts custom request ID and authorization headers. #### Method GET #### Endpoint /items #### Parameters ##### Path Parameters None ##### Query Parameters - **limit** (int) - Optional - The maximum number of items to return (default: 20, min: 1, max: 100). - **offset** (int) - Optional - The number of items to skip (default: 0, min: 0). - **sort_by** (string) - Optional - The field to sort the items by. ##### Request Body None ##### Headers - **x-request-id** (string) - Optional - A custom identifier for the request. - **authorization** (string) - Optional - The authorization token for the request. ### Response #### Success Response (200) - **items** (array) - A list of items. - **id** (integer) - The ID of the item. - **pagination** (object) - Pagination details. - **limit** (integer) - The limit applied to the pagination. - **offset** (integer) - The offset applied to the pagination. - **request_id** (string) - The request ID, if provided. #### Response Example ```json { "items": [ {"id": 5}, {"id": 6}, // ... more items ], "pagination": { "limit": 10, "offset": 5 }, "request_id": "abc123" } ``` ``` -------------------------------- ### Extract Query and Header Parameters Source: https://context7.com/romayuhym/wellapi/llms.txt Demonstrates how to use `Query` and `Header` annotations in WellAPI to extract and validate parameters from the query string and HTTP headers. It shows how to define default values and aliases. ```python from typing import Annotated from pydantic import BaseModel, Field from wellapi import WellApi, Query, Header app = WellApi(title="API", version="1.0.0") class PaginationParams(BaseModel): limit: int = Field(20, ge=1, le=100) offset: int = Field(0, ge=0) sort_by: str | None = None @app.get("/items") def list_items( params: Annotated[PaginationParams, Query()], x_request_id: Annotated[str | None, Header(alias="x-request-id")] = None, authorization: Annotated[str | None, Header()] = None, ): return { "items": [{"id": i} for i in range(params.offset, params.offset + params.limit)], "pagination": {"limit": params.limit, "offset": params.offset}, "request_id": x_request_id, } # curl "https://api.example.com/items?limit=10&offset=5&sort_by=name" -H "x-request-id: abc123" # Output: {"items": [{"id": 5}, {"id": 6}, ...], "pagination": {"limit": 10, "offset": 5}, "request_id": "abc123"} ``` -------------------------------- ### WellAPI: Response Model Annotation Source: https://github.com/romayuhym/wellapi/blob/main/docs/framework-usage.md Shows how to specify response models in WellAPI using Python's return type annotations. The `UserOut` model is used to define the structure of the response from the `profile` endpoint. ```python @app.get("/profile") def profile() -> UserOut: return UserOut(id=7, name="Jane") ``` -------------------------------- ### Dependency Injection with Depends in WellAPI Source: https://context7.com/romayuhym/wellapi/llms.txt Illustrates dependency injection using the `Depends` class in WellAPI. Enables reusable logic for database connections, repositories, and settings. Shows simple, sub-dependency, and class-based dependencies. ```python from typing import Annotated from wellapi import WellApi from wellapi.params import Depends app = WellApi(title="API", version="1.0.0") # Simple dependency def get_db_session(): return {"connection": "postgres://localhost/mydb"} # Dependency with sub-dependency def get_user_repository(db: Annotated[dict, Depends(get_db_session)]): return {"db": db, "table": "users"} # Class-based dependency class Settings: def __init__(self): self.api_key = "secret-key" self.debug = True def get_settings(): return Settings() @app.get("/users") def list_users( repo: Annotated[dict, Depends(get_user_repository)], settings: Annotated[Settings, Depends(get_settings)], ): return { "users": [{"id": 1, "name": "Alice"}], "repository": repo, "debug_mode": settings.debug, } # curl https://api.example.com/users # Output: {"users": [{"id": 1, "name": "Alice"}], "repository": {"db": {...}, "table": "users"}, "debug_mode": true} ``` -------------------------------- ### API Key Header Authentication Source: https://context7.com/romayuhym/wellapi/llms.txt Explains how to implement API key authentication using the `APIKeyHeader` class, which handles missing or invalid keys by raising 403 errors. ```APIDOC ## GET /protected ### Description An endpoint protected by API key authentication via the 'x-api-key' header. ### Method GET ### Endpoint /protected ### Parameters #### Header Parameters - **x-api-key** (string) - Required - API Key for authentication. ### Request Example ```bash curl https://api.example.com/protected -H "x-api-key: secret-key-123" ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating access granted. #### Response Example ```json { "message": "Access granted" } ``` #### Error Response (403) - **detail** (string) - "Not authenticated" if the API key is missing or invalid. ## GET /admin ### Description An endpoint that requires a valid API key for administrative access. ### Method GET ### Endpoint /admin ### Parameters #### Header Parameters - **x-api-key** (string) - Required - API Key for authentication. ### Response #### Success Response (200) - **message** (string) - A message indicating admin access. - **key_used** (string) - The API key that was used for authentication. #### Response Example ```json { "message": "Admin access", "key_used": "admin-key-456" } ``` ``` -------------------------------- ### AWS CDK Integration Source: https://context7.com/romayuhym/wellapi/llms.txt Deploy WellAPI applications using the `WellApiCDK` construct for infrastructure-as-code. ```APIDOC ## AWS CDK Integration ### Description Deploy WellAPI applications using the `WellApiCDK` construct for infrastructure-as-code. ### Usage ```python from aws_cdk import Stack, App from constructs import Construct from wellapi.build.cdk import WellApiCDK class ApiStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) WellApiCDK( self, "MyApi", app_srt="main:app", handlers_dir="handlers", cors=True, cache_enable=True, log_enable=True, ) # Deploy with CDK # cdk deploy ApiStack app = App() ApiStack(app, "ApiStack") app.synth() ``` ``` -------------------------------- ### AWS CDK Stack for WellAPI Deployment Source: https://github.com/romayuhym/wellapi/blob/main/README.md Defines an AWS CDK stack to deploy a WellAPI application. It configures essential parameters like the app entry point, handlers directory, CORS, and logging. ```python from aws_cdk import Stack from constructs import Construct from wellapi.build.cdk import WellApiCDK class MyStack(Stack): def __init__(self, scope: Construct, id_: str, **kwargs) -> None: super().__init__(scope, id_, **kwargs) WellApiCDK( self, "WellApiCDK", app_srt="main:app", handlers_dir="handlers", cors=True, cache_enable=False, log_enable=True, ) ``` -------------------------------- ### Typed Path Parameters Source: https://context7.com/romayuhym/wellapi/llms.txt Demonstrates how to define path parameters with automatic type conversion in WellAPI. Supported types include str, int, float, uuid, and path. ```APIDOC ## GET /users/{user_id:int} ### Description Retrieves a user by their integer ID. ### Method GET ### Endpoint /users/{user_id:int} ### Parameters #### Path Parameters - **user_id** (int) - Required - The unique identifier for the user. ### Request Example ```bash curl https://api.example.com/users/42 ``` ### Response #### Success Response (200) - **user_id** (integer) - The ID of the user. - **type** (string) - Indicates the type of the user_id parameter (e.g., "integer"). #### Response Example ```json { "user_id": 42, "type": "integer" } ``` ## GET /products/{product_id:uuid} ### Description Retrieves a product by its UUID. ### Method GET ### Endpoint /products/{product_id:uuid} ### Parameters #### Path Parameters - **product_id** (uuid) - Required - The unique identifier for the product. ### Request Example ```bash curl https://api.example.com/products/550e8400-e29b-41d4-a716-446655440000 ``` ### Response #### Success Response (200) - **product_id** (string) - The UUID of the product. #### Response Example ```json { "product_id": "550e8400-e29b-41d4-a716-446655440000" } ``` ## GET /files/{file_path:path} ### Description Retrieves a file using its path. ### Method GET ### Endpoint /files/{file_path:path} ### Parameters #### Path Parameters - **file_path** (path) - Required - The path to the file. ### Request Example ```bash curl https://api.example.com/files/documents/reports/2024/q1.pdf ``` ### Response #### Success Response (200) - **path** (string) - The path of the requested file. #### Response Example ```json { "path": "documents/reports/2024/q1.pdf" } ``` ``` -------------------------------- ### CLI: Generate OpenAPI Specification Source: https://context7.com/romayuhym/wellapi/llms.txt Commands to generate OpenAPI 3.0 specifications compatible with AWS API Gateway. ```APIDOC ## CLI: Generate OpenAPI Specification ### Description The `wellapi openapi` command generates OpenAPI 3.0 specifications compatible with AWS API Gateway. ### Usage ```bash # Basic usage: generate openapi.json from main.py app and handlers/ directory wellapi openapi main:app handlers --output openapi.json # With CORS enabled and custom IAM role wellapi openapi main:app handlers --output openapi.json --cors true --role_name MyLambdaRole # Custom app location wellapi openapi src.api.main:application api/handlers --output spec.json ``` ``` -------------------------------- ### RequestAPIGateway and ResponseAPIGateway Models Source: https://context7.com/romayuhym/wellapi/llms.txt Demonstrates the use of `RequestAPIGateway` and `ResponseAPIGateway` models in WellAPI. The `request_info` endpoint shows how to access raw AWS event data like HTTP method, path, query parameters, headers, and source IP. The `custom_response` endpoint illustrates creating a custom `ResponseAPIGateway` object with specific content, status code, and headers. ```python from wellapi import WellApi, RequestAPIGateway, ResponseAPIGateway app = WellApi(title="API", version="1.0.0") @app.get("/request-info") def request_info(request: RequestAPIGateway): return { "method": request.raw_event.httpMethod, "path": request.raw_event.path, "query_params": dict(request.query_params), "headers": dict(request.headers), "source_ip": request.raw_event.requestContext.get("identity", {}).get("sourceIp"), } @app.get("/custom-response") def custom_response() -> ResponseAPIGateway: return ResponseAPIGateway( content={"custom": "response"}, status_code=200, headers={"x-custom-header": "value", "cache-control": "max-age=3600"} ) # curl https://api.example.com/custom-response -v # Response includes custom headers: x-custom-header: value, cache-control: max-age=3600 ``` -------------------------------- ### Generate OpenAPI Specification using CLI Source: https://context7.com/romayuhym/wellapi/llms.txt Generates OpenAPI 3.0 specifications compatible with AWS API Gateway using the `wellapi openapi` command. This command takes the main application file and handler directory as input and can be configured with options for CORS and custom IAM roles. ```bash # Basic usage: generate openapi.json from main.py app and handlers/ directory wellapi openapi main:app handlers --output openapi.json # With CORS enabled and custom IAM role wellapi openapi main:app handlers --output openapi.json --cors true --role_name MyLambdaRole # Custom app location wellapi openapi src.api.main:application api/handlers --output spec.json ``` -------------------------------- ### OpenTelemetry Integration Source: https://context7.com/romayuhym/wellapi/llms.txt Enable distributed tracing and metrics with the optional telemetry module using OpenTelemetry providers. ```APIDOC ## OpenTelemetry Integration Enable distributed tracing and metrics with the optional telemetry module using OpenTelemetry providers. **Installation:** ```bash pip install "wellapi[telemetry]" ``` **Usage:** Import and configure OpenTelemetry `TracerProvider` and `MeterProvider` to integrate with WellAPI's telemetry module. ``` -------------------------------- ### AWS CDK Integration for Deployment Source: https://context7.com/romayuhym/wellapi/llms.txt Deploys WellAPI applications using the `WellApiCDK` construct for infrastructure-as-code with AWS CDK. This Python code defines a CDK stack that provisions the necessary AWS resources for a WellAPI application, including options for CORS, caching, and logging. ```python from aws_cdk import Stack, App from constructs import Construct from wellapi.build.cdk import WellApiCDK class ApiStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) WellApiCDK( self, "MyApi", app_srt="main:app", handlers_dir="handlers", cors=True, cache_enable=True, log_enable=True, ) # Deploy with CDK # cdk deploy ApiStack app = App() ApiStack(app, "ApiStack") app.synth() ``` -------------------------------- ### TestClient for Local Testing Source: https://context7.com/romayuhym/wellapi/llms.txt The `TestClient` class wraps httpx to enable testing WellAPI applications without deploying to AWS. It allows simulating requests and inspecting responses. ```APIDOC ## TestClient for Local Testing The `TestClient` class wraps httpx to enable testing WellAPI applications without deploying to AWS. ### Testing Endpoints **GET /items/{item_id:int}** **Description:** Retrieves an item by its ID. **Method:** GET **Endpoint:** `/items/{item_id:int}` **Parameters:** #### Path Parameters - **item_id** (int) - Required - The ID of the item to retrieve. **POST /items** **Description:** Creates a new item. **Method:** POST **Endpoint:** `/items` **Parameters:** #### Request Body - **item** (Item) - Required - The item data to create. **Example Usage:** ```python from wellapi.testclient import TestClient client = TestClient(app) # Test GET request response = client.get("/items/42") assert response.status_code == 200 assert response.json() == {"id": 42, "name": "Item 42"} # Test POST request response = client.post("/items", json={"id": 1, "name": "New Item"}) assert response.status_code == 201 assert response.json() == {"id": 1, "name": "New Item"} # Test with headers response = client.get("/items/1", headers={"x-request-id": "test-123"}) assert response.status_code == 200 # Test SQS handler (example) response = client.post("/queue_/my-queue", json=[{"event": "data"}]) # Test scheduled job (example) response = client.post("/job_/my-job") ``` ```