### Complete Health Check Setup Example - Python Source: https://bolt.farhana.li/topics/health-checks A comprehensive example demonstrating the setup of Django-Bolt health checks. It includes registering the default endpoints and adding custom asynchronous checks for database, Redis, and Celery, ensuring robust application monitoring. ```python from django_bolt import BoltAPI from django_bolt.health import register_health_checks, add_health_check api = BoltAPI() # Register health endpoints register_health_checks(api) # Add database check async def check_database(): try: from django.db import connection await connection.ensure_connection() return True, "Database OK" except Exception as e: return False, f"Database error: {e}" # Add Redis check async def check_redis(): try: import redis r = redis.Redis() r.ping() return True, "Redis OK" except Exception as e: return False, f"Redis error: {e}" # Add message queue check async def check_celery(): try: from celery import current_app current_app.control.ping(timeout=1) return True, "Celery OK" except Exception as e: return False, f"Celery error: {e}" add_health_check(check_database) add_health_check(check_redis) add_health_check(check_celery) ``` -------------------------------- ### GET /go Source: https://bolt.farhana.li/getting-started/quickstart Redirects the user to the status page. ```APIDOC ## GET /go ### Description Redirects the user to the status page. ### Method GET ### Endpoint /go ### Parameters None ### Request Body None ### Response #### Success Response (307 Temporary Redirect) - **Location** header - Set to `/status-page`. #### Response Example ``` HTTP/1.1 307 Temporary Redirect Location: /status-page ``` ``` -------------------------------- ### All HTTP Methods Example Source: https://bolt.farhana.li/topics/routing Demonstrates the usage of all common HTTP methods (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS) for managing items. ```APIDOC ## GET /items ### Description Retrieves a list of items. ### Method GET ### Endpoint /items ### Parameters ### Request Body ### Request Example ### Response #### Success Response (200) - **items** (array) - A list of item objects. #### Response Example ```json { "items": [] } ``` ## POST /items ### Description Creates a new item. ### Method POST ### Endpoint /items ### Parameters ### Request Body ### Request Example ### Response #### Success Response (200) - **created** (boolean) - Indicates if the item was successfully created. #### Response Example ```json { "created": true } ``` ## PUT /items/{item_id} ### Description Replaces an existing item with the provided data. ### Method PUT ### Endpoint /items/{item_id} ### Parameters #### Path Parameters - **item_id** (integer) - Required - The ID of the item to replace. ### Request Body ### Request Example ### Response #### Success Response (200) - **replaced** (boolean) - Indicates if the item was successfully replaced. #### Response Example ```json { "replaced": true } ``` ## PATCH /items/{item_id} ### Description Partially updates an existing item. ### Method PATCH ### Endpoint /items/{item_id} ### Parameters #### Path Parameters - **item_id** (integer) - Required - The ID of the item to update. ### Request Body ### Request Example ### Response #### Success Response (200) - **updated** (boolean) - Indicates if the item was successfully updated. #### Response Example ```json { "updated": true } ``` ## DELETE /items/{item_id} ### Description Deletes an item. ### Method DELETE ### Endpoint /items/{item_id} ### Parameters #### Path Parameters - **item_id** (integer) - Required - The ID of the item to delete. ### Request Body ### Request Example ### Response #### Success Response (200) - **deleted** (boolean) - Indicates if the item was successfully deleted. #### Response Example ```json { "deleted": true } ``` ## HEAD /items ### Description Retrieves only the headers for the items resource. ### Method HEAD ### Endpoint /items ### Parameters ### Request Body ### Request Example ### Response #### Success Response (200) (No body content for HEAD requests) #### Response Example ## OPTIONS /items ### Description Retrieves the allowed HTTP methods for the items resource. ### Method OPTIONS ### Endpoint /items ### Parameters ### Request Body ### Request Example ### Response #### Success Response (200) - **headers** (object) - Contains an 'Allow' header specifying the allowed HTTP methods. #### Response Example ```json { "headers": { "Allow": "GET, POST, PUT, PATCH, DELETE" } } ``` ``` -------------------------------- ### Install Django-Bolt using uv Source: https://bolt.farhana.li/index This snippet demonstrates how to install the Django-Bolt package using the uv package installer. ```bash uv add django-bolt ``` -------------------------------- ### GET / Source: https://bolt.farhana.li/getting-started/quickstart Retrieves the overall status of the Mission Control system. ```APIDOC ## GET / ### Description Retrieves the overall status of the Mission Control system. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The operational status of the system. - **message** (string) - A human-readable message indicating the system is online. #### Response Example { "status": "operational", "message": "Mission Control Online" } ``` -------------------------------- ### Create Logging Middleware (Quick Start) Source: https://bolt.farhana.li/topics/logging Demonstrates how to create a logging middleware instance with default settings. ```APIDOC ## Create Logging Middleware (Quick Start) ### Description This section shows how to quickly set up the logging middleware with its default configuration. ### Method `create_logging_middleware()` ### Endpoint N/A (This is a Python function call) ### Parameters None ### Request Example ```python from django_bolt.logging import create_logging_middleware middleware = create_logging_middleware() ``` ### Response N/A (Returns a middleware instance) ``` -------------------------------- ### Install Django-Bolt using Pip Source: https://bolt.farhana.li/index This snippet shows how to install the Django-Bolt package using the pip package installer. ```bash pip install django-bolt ``` -------------------------------- ### POST /missions Source: https://bolt.farhana.li/getting-started/quickstart Creates a new mission. ```APIDOC ## POST /missions ### Description Creates a new mission. ### Method POST ### Endpoint /missions ### Parameters #### Request Body - **name** (string) - Required - The name of the mission. - **description** (string) - Optional - A detailed description of the mission. - **launch_date** (string) - Optional - The planned launch date of the mission (YYYY-MM-DD). ### Request Example ```json { "name": "Voyager 3", "description": "A mission to explore the outer reaches of the solar system.", "launch_date": "2030-01-15" } ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the newly created mission. - **name** (string) - The name of the mission. - **status** (string) - The initial status of the mission (defaults to 'planned'). #### Response Example { "id": 2, "name": "Voyager 3", "status": "planned" } ``` -------------------------------- ### Django Template Example Source: https://bolt.farhana.li/topics/responses An example of a standard Django template file that can be rendered by Django-Bolt's `render` function. It demonstrates basic template variables and loops. ```html {{ title }}

{{ title }}

``` -------------------------------- ### Path Parameters Example Source: https://bolt.farhana.li/topics/routing Illustrates how to define endpoints with path parameters to capture dynamic URL segments. ```APIDOC ## GET /users/{user_id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (integer) - Required - The ID of the user to retrieve. ### Request Body ### Request Example ### Response #### Success Response (200) - **user_id** (integer) - The ID of the user. #### Response Example ```json { "user_id": 123 } ``` ## GET /posts/{post_id}/comments/{comment_id} ### Description Retrieves a specific comment for a given post. ### Method GET ### Endpoint /posts/{post_id}/comments/{comment_id} ### Parameters #### Path Parameters - **post_id** (integer) - Required - The ID of the post. - **comment_id** (integer) - Required - The ID of the comment. ### Request Body ### Request Example ### Response #### Success Response (200) - **post_id** (integer) - The ID of the post. - **comment_id** (integer) - The ID of the comment. #### Response Example ```json { "post_id": 456, "comment_id": 789 } ``` ``` -------------------------------- ### GET /missions Source: https://bolt.farhana.li/getting-started/quickstart Lists available missions, with optional filtering by status and limit. ```APIDOC ## GET /missions ### Description Lists available missions, with optional filtering by status and limit. ### Method GET ### Endpoint /missions ### Parameters #### Query Parameters - **status** (string) - Optional. Filters missions by their status (e.g., 'active', 'completed'). - **limit** (integer) - Optional. The maximum number of missions to return. ### Request Example None ### Response #### Success Response (200) - **missions** (array) - A list of mission objects. - **id** (integer) - The unique identifier for the mission. - **name** (string) - The name of the mission. - **status** (string) - The current status of the mission. - **count** (integer) - The total number of missions returned. #### Response Example { "missions": [ { "id": 1, "name": "Apollo 11", "status": "completed" } ], "count": 1 } ``` -------------------------------- ### Making GET Requests with TestClient Source: https://bolt.farhana.li/topics/testing Illustrates how to perform GET requests using TestClient, including simple requests, requests with query parameters, and requests with custom headers. ```python with TestClient(api) as client: # Simple GET response = client.get("/users") # GET with query parameters response = client.get("/search?q=test&limit=20") # GET with headers response = client.get("/secure", headers={"Authorization": "Bearer token"}) ``` -------------------------------- ### GET /users Source: https://bolt.farhana.li/topics/dependencies Retrieves a list of the first 10 users from the database. ```APIDOC ## GET /users ### Description Retrieves a list of the first 10 users from the database. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed" } ``` ### Response #### Success Response (200) - **list** (list) - A list of user objects. #### Response Example ```json { "example": "[{"id": 1, "username": "alice"}, {"id": 2, "username": "bob"}]" } ``` ``` -------------------------------- ### Systemd Service Configuration for Django-Bolt Source: https://bolt.farhana.li/getting-started/deployment Configure Django-Bolt to run as a managed service using systemd. This setup ensures the application starts automatically on boot and restarts if it crashes. The configuration defines user, working directory, and the command to execute, including host, port, and process count for the Django-Bolt server. ```systemd [Unit] Description=Django-Bolt API Server After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/path/to/your/project ExecStart=/path/to/venv/bin/python manage.py runbolt --host 127.0.0.1 --port 8000 --processes 4 Restart=always RestartSec=3 [Install] WantedBy=multi-user.target ``` -------------------------------- ### Create Mission Source: https://bolt.farhana.li/getting-started/quickstart Create a new mission with specified details. ```APIDOC ## POST /missions ### Description Create a new mission with specified details. ### Method POST ### Endpoint /missions ### Parameters #### Request Body - **name** (str) - Required - The name of the mission (1-100 characters). Cannot start with 'test'. - **description** (str) - Optional - A description of the mission (max 500 characters). - **launch_date** (datetime) - Optional - The scheduled launch date of the mission. ### Request Example ```json { "name": "New Horizon Mission", "description": "Exploration of the Kuiper Belt.", "launch_date": "2025-01-15T10:00:00" } ``` ### Response #### Success Response (200 or 201) - **mission_id** (int) - The unique identifier for the newly created mission. - **name** (str) - The name of the mission. - **description** (str) - A detailed description of the mission. - **launch_date** (datetime) - The scheduled launch date of the mission. #### Response Example ```json { "mission_id": 2, "name": "New Horizon Mission", "description": "Exploration of the Kuiper Belt.", "launch_date": "2025-01-15T10:00:00" } ``` ``` -------------------------------- ### Redirect to Dashboard Source: https://bolt.farhana.li/getting-started/quickstart Redirects the user to the main dashboard page. ```APIDOC ## GET /websites/bolt_farhana_li/go ### Description Redirects the user to the application's dashboard. ### Method GET ### Endpoint /websites/bolt_farhana_li/go ### Response #### Success Response (302 Redirect) - Redirects to `/dashboard`. ### Request Example (No request body for this GET request) ### Response Example (Redirects to /dashboard) ``` -------------------------------- ### WebSocket Route Example Source: https://bolt.farhana.li/topics/routing Defines a WebSocket endpoint for real-time communication, demonstrating an echo server functionality. ```APIDOC ## WebSocket /ws/echo ### Description An echo WebSocket endpoint that sends back any received text message. ### Method WebSocket ### Endpoint /ws/echo ### Parameters ### Request Body ### Request Example (WebSocket connection) ### Response #### Success Response - **sent_text** (string) - The echoed text message received from the client. #### Response Example (Client sends: "Hello") (Server echoes: "Echo: Hello") ``` -------------------------------- ### Status Page Source: https://bolt.farhana.li/getting-started/quickstart Returns a status page indicating that all systems are operational. ```APIDOC ## GET /websites/bolt_farhana_li/status-page ### Description Displays a status page confirming all systems are operational. ### Method GET ### Endpoint /websites/bolt_farhana_li/status-page ### Response #### Success Response (200) - Returns an HTML page with the message "Mission Control: All Systems Operational". ### Request Example (No request body for this GET request) ### Response Example ```html

Mission Control: All Systems Operational

``` ``` -------------------------------- ### Create Astronaut Source: https://bolt.farhana.li/getting-started/quickstart Register a new astronaut for a mission. ```APIDOC ## POST /astronauts ### Description Register a new astronaut for a mission. ### Method POST ### Endpoint /astronauts ### Parameters #### Request Body - **name** (str) - Required - The name of the astronaut (1-100 characters). - **role** (str) - Required - The role of the astronaut (e.g., 'Commander', 'Pilot', 'Mission Specialist', 'Flight Engineer'). ### Request Example ```json { "name": "Buzz Aldrin", "role": "Pilot" } ``` ### Response #### Success Response (200 or 201) - **astronaut_id** (int) - The unique identifier for the newly created astronaut. - **name** (str) - The name of the astronaut. - **role** (str) - The role of the astronaut. #### Response Example ```json { "astronaut_id": 1, "name": "Buzz Aldrin", "role": "Pilot" } ``` ``` -------------------------------- ### GET /items Source: https://bolt.farhana.li/topics/dependencies Retrieves a paginated list of items from the database. ```APIDOC ## GET /items ### Description Retrieves a paginated list of items from the database. Supports custom page and page_size parameters. ### Method GET ### Endpoint /items ### Parameters #### Query Parameters - **page** (int) - Optional - The page number to retrieve (defaults to 1). - **page_size** (int) - Optional - The number of items per page (defaults to 20, max 100). #### Request Body None ### Request Example ```json { "example": "No request body needed" } ``` ### Response #### Success Response (200) - **page** (int) - The current page number. - **items** (list) - A list of item objects. #### Response Example ```json { "example": "{\"page\": 1, \"items\": [{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]}" } ``` ``` -------------------------------- ### Custom Error Handling Example Source: https://bolt.farhana.li/topics/error-handling An example demonstrating how to use custom HTTP exceptions like BadRequest and NotFound within a BoltAPI application. ```APIDOC ## Example: Custom Error Handling ### Description This example shows how to define API endpoints using `BoltAPI` and raise custom HTTP exceptions for specific error conditions. ### Setup ```python from django_bolt import BoltAPI from django_bolt.exceptions import HTTPException, NotFound, BadRequest # Assuming User and Order models and OrderCreate schema are defined elsewhere api = BoltAPI() ``` ### GET /users/{user_id} Handles retrieving a user by ID, raising `BadRequest` for invalid IDs and `NotFound` if the user does not exist. ```python @api.get("/users/{user_id}") async def get_user(user_id: int): if user_id < 1: raise BadRequest( detail="Invalid user ID", extra={"user_id": user_id, "reason": "Must be positive"} ) # Assuming User.objects.filter(...).afirst() retrieves a user user = await User.objects.filter(id=user_id).afirst() if not user: raise NotFound(detail=f"User {user_id} not found") return {"id": user.id, "username": user.username} ``` ### POST /orders Handles creating an order, raising `BadRequest` if an `IntegrityError` occurs during creation. ```python @api.post("/orders") async def create_order(data: OrderCreate): # Assuming OrderCreate is a Pydantic or similar model try: # Assuming Order.objects.acreate creates an order order = await Order.objects.acreate(**data.__dict__) return {"id": order.id} except IntegrityError: raise BadRequest( detail="Order creation failed", extra={"reason": "Duplicate order reference"} ) ``` ``` -------------------------------- ### Item ViewSet (GET /items) Source: https://bolt.farhana.li/topics/dependencies Provides a ViewSet for managing items with pagination support. ```APIDOC ## Item ViewSet (GET /items) ### Description Provides a ViewSet for managing items, including a list endpoint with pagination. ### Method GET ### Endpoint /items ### Parameters #### Query Parameters - **page** (int) - Optional - The page number to retrieve (defaults to 1). - **page_size** (int) - Optional - The number of items per page (defaults to 20, max 100). #### Request Body None ### Request Example ```json { "example": "No request body needed" } ``` ### Response #### Success Response (200) - **list** (list) - A list of item objects, each with an 'id' and 'name'. #### Response Example ```json { "example": "[{"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}]" } ``` ``` -------------------------------- ### GET /info - Request Info Source: https://bolt.farhana.li/topics/requests Retrieves basic information about the incoming request, including its method and path. ```APIDOC ## GET /info ### Description Retrieves basic information about the incoming request, including its method and path. ### Method GET ### Endpoint /info ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **method** (str) - The HTTP method of the request. - **path** (str) - The path of the request. #### Response Example ```json { "method": "GET", "path": "/info" } ``` ``` -------------------------------- ### GET / Source: https://bolt.farhana.li/getting-started/quickstart Retrieves the operational status of the Mission Control system. ```APIDOC ## GET / ### Description Retrieves the operational status of the Mission Control system. ### Method GET ### Endpoint / ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - The operational status of Mission Control. - **message** (string) - A human-readable message indicating the system's status. #### Response Example { "status": "operational", "message": "Mission Control Online" } ``` -------------------------------- ### Create Django App using manage.py Source: https://bolt.farhana.li/getting-started/quickstart This command initiates a new Django application within the existing project, which will house the models and API logic for the space missions. ```bash python manage.py startapp missions ``` -------------------------------- ### POST /missions/{mission_id}/patch Source: https://bolt.farhana.li/getting-started/quickstart Uploads a patch file for a specific mission. ```APIDOC ## POST /missions/{mission_id}/patch ### Description Uploads a patch file for a specific mission. ### Method POST ### Endpoint /missions/{mission_id}/patch ### Parameters #### Path Parameters - **mission_id** (integer) - Required - The unique identifier of the mission. #### Request Body - **patch** (file) - Required - The patch file to upload. This should be a multipart/form-data request. ### Request Example ``` POST /missions/1/patch Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW ------WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="patch"; filename="patch.png" Content-Type: image/png [Binary file content] ------WebKitFormBoundary7MA4YWxkTrZu0gW-- ``` ### Response #### Success Response (200) - **message** (string) - A confirmation message indicating the patch was uploaded. - **filename** (string) - The name of the uploaded patch file. #### Response Example { "message": "Patch uploaded", "filename": "patch.png" } ``` -------------------------------- ### Route Options Example Source: https://bolt.farhana.li/topics/routing Shows how to configure route decorators with options like status code, summary, description, tags, and response models. ```APIDOC ## GET /users/{user_id} ### Description Retrieves a user by their ID. This detailed description appears in OpenAPI documentation. ### Method GET ### Endpoint /users/{user_id} ### Parameters #### Path Parameters - **user_id** (integer) - Required - The ID of the user to retrieve. ### Request Body ### Request Example ### Response #### Success Response (200) - **user_id** (integer) - The ID of the user. #### Response Example ```json { "user_id": 123 } ``` **OpenAPI Metadata:** - **Summary**: Get user - **Description**: Get a user by ID - **Tags**: users - **Response Model**: UserSchema ``` -------------------------------- ### GET /missions/{mission_id} Source: https://bolt.farhana.li/getting-started/quickstart Retrieves detailed information about a specific mission. ```APIDOC ## GET /missions/{mission_id} ### Description Retrieves detailed information about a specific mission. ### Method GET ### Endpoint /missions/{mission_id} ### Parameters #### Path Parameters - **mission_id** (integer) - Required - The unique identifier of the mission. ### Request Example None ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the mission. - **name** (string) - The name of the mission. - **status** (string) - The current status of the mission. - **launch_date** (string) - The planned launch date of the mission (YYYY-MM-DD). - **description** (string) - A detailed description of the mission. #### Response Example { "id": 1, "name": "Apollo 11", "status": "completed", "launch_date": "1969-07-16", "description": "First manned mission to land on the Moon." } ``` -------------------------------- ### GET /missions/{mission_id}/log Source: https://bolt.farhana.li/getting-started/quickstart Retrieves the operational log for a specific mission. ```APIDOC ## GET /missions/{mission_id}/log ### Description Retrieves the operational log for a specific mission. ### Method GET ### Endpoint /missions/{mission_id}/log ### Parameters #### Path Parameters - **mission_id** (integer) - Required - The unique identifier of the mission. ### Request Example None ### Response #### Success Response (200) - The response body is plain text containing the mission log. #### Response Example ``` === MISSION LOG: Apollo 11 === Status: COMPLETED ``` ``` -------------------------------- ### Run Django-Bolt Management Command Source: https://bolt.farhana.li/ref/settings Examples of using the `runbolt` management command with various options for development, production scaling, and custom host/port binding. ```bash # Development with auto-reload python manage.py runbolt --dev ``` ```bash # Production with scaling python manage.py runbolt --processes 4 --workers 2 ``` ```bash # Custom bind address python manage.py runbolt --host 127.0.0.1 --port 3000 ``` -------------------------------- ### Custom Actions - Collection Action Example Source: https://bolt.farhana.li/topics/class-based-views Demonstrates how to create a collection action (GET /articles/published) using the @action decorator. ```APIDOC ## GET /articles/published ### Description Retrieves a list of published articles. ### Method GET ### Endpoint /articles/published ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **articles** (list) - A list of published articles, each with 'id' and 'title'. #### Response Example ```json { "articles": [ { "id": 1, "title": "First Article" }, { "id": 2, "title": "Second Article" } ] } ``` ``` -------------------------------- ### GET /missions/{mission_id} Source: https://bolt.farhana.li/getting-started/quickstart Retrieves details for a specific space mission identified by its ID. ```APIDOC ## GET /missions/{mission_id} ### Description Retrieves details for a specific space mission identified by its ID. Includes mission name, status, launch date, description, and associated astronauts. ### Method GET ### Endpoint /missions/{mission_id} ### Parameters #### Path Parameters - **mission_id** (integer) - Required - The unique identifier for the mission. #### Query Parameters None ### Request Example None ### Response #### Success Response (200) - **id** (integer) - The unique identifier for the mission. - **name** (string) - The name of the mission. - **status** (string) - The current status of the mission (e.g., planned, active, completed, aborted). - **launch_date** (string) - The planned or actual launch date of the mission (ISO format), or null if not set. - **description** (string) - A detailed description of the mission. #### Response Example { "id": 1, "name": "Apollo 11", "status": "completed", "launch_date": "1969-07-16T00:00:00", "description": "The first manned mission to land on the Moon." } #### Error Response - **404 Not Found**: If a mission with the specified ID does not exist. - **422 Unprocessable Entity**: If the `mission_id` is not a valid integer. ``` -------------------------------- ### Get Mission Details Source: https://bolt.farhana.li/getting-started/quickstart Retrieve detailed information about a specific space mission using its ID. ```APIDOC ## GET /missions/{mission_id} ### Description Retrieve detailed information about a specific space mission. ### Method GET ### Endpoint /missions/{mission_id} ### Parameters #### Path Parameters - **mission_id** (int) - Required - The unique identifier for the mission. ### Request Example (No request body for GET request) ### Response #### Success Response (200) - **mission_id** (int) - The unique identifier for the mission. - **name** (str) - The name of the mission. - **description** (str) - A detailed description of the mission. - **launch_date** (datetime) - The scheduled launch date of the mission. #### Response Example { "mission_id": 1, "name": "Apollo 11", "description": "First crewed mission to land on the Moon.", "launch_date": "1969-07-16T13:32:00" } ``` -------------------------------- ### LoggingMiddleware - Using with Handlers Source: https://bolt.farhana.li/topics/logging Demonstrates how to manually log requests and responses using the `LoggingMiddleware` instance. ```APIDOC ## LoggingMiddleware - Using with Handlers ### Description This section shows how to use the `LoggingMiddleware` instance to manually log request and response events, typically within application logic. ### Method `middleware.log_request(...)` and `middleware.log_response(...)` ### Endpoint N/A (This is a Python class method call) ### Parameters * `log_request` requires: * `request` (dict): A dictionary containing request details (e.g., `"method"`, `"path"`, `"headers"`). * `log_response` requires: * `request` (dict): A dictionary containing the original request details. * `status_code` (int): The HTTP status code of the response. * `duration` (float): The duration of the request in seconds. ### Request Example ```python from django_bolt import BoltAPI from django_bolt.logging import LoggingConfig, LoggingMiddleware config = LoggingConfig( logger_name="myapp.api", skip_paths={"/health"}, ) middleware = LoggingMiddleware(config) # Log request middleware.log_request({ "method": "POST", "path": "/api/users", "headers": {"content-type": "application/json"}, }) # Log response middleware.log_response( request={"method": "POST", "path": "/api/users"}, status_code=201, duration=0.05, # seconds ) ``` ### Response N/A (Logs are generated based on the method calls) ``` -------------------------------- ### Setup Queue-Based Logging in Python Source: https://bolt.farhana.li/topics/logging Initializes Django-Bolt's queue-based logging system. This is typically called automatically by runbolt and ensures that log I/O operations do not block request handling by offloading them to a background thread. ```python from django_bolt.logging.config import setup_django_logging # Called automatically by runbolt setup_django_logging() ``` -------------------------------- ### GET /missions/{mission_id}/classified Source: https://bolt.farhana.li/getting-started/quickstart Retrieves classified information for a specific mission, requiring specific clearance. ```APIDOC ## GET /missions/{mission_id}/classified ### Description Retrieves classified information for a specific mission, requiring specific clearance. ### Method GET ### Endpoint /missions/{mission_id}/classified ### Parameters #### Path Parameters - **mission_id** (integer) - Required - The unique identifier of the mission. #### Headers - **X-Clearance-Level** (string) - Required - The clearance level of the requester. Must be 'top-secret' or 'confidential'. ### Request Example ``` GET /missions/1/classified Headers: X-Clearance-Level: top-secret ``` ### Response #### Success Response (200) - **mission** (string) - The name of the mission. - **classified_data** (string) - The classified information related to the mission. #### Response Example { "mission": "Apollo 11", "classified_data": "Launch codes: APOLLO-7749-OMEGA" } ``` -------------------------------- ### Add Django App to INSTALLED_APPS Source: https://bolt.farhana.li/getting-started/quickstart After creating the missions app, it needs to be registered in the project's `settings.py` file by adding it to the `INSTALLED_APPS` list. This ensures Django recognizes and loads the app. ```python INSTALLED_APPS = [ ... "django_bolt", "missions", ] ``` -------------------------------- ### APIView Basics Source: https://bolt.farhana.li/topics/class-based-views Use APIView to group HTTP methods for a single resource. This example shows how to handle GET and POST requests for a '/hello' endpoint. ```APIDOC ## APIView Basics ### Description Use `APIView` to group HTTP methods for a single resource. This example demonstrates handling GET and POST requests for a '/hello' endpoint. ### Method GET, POST ### Endpoint - `/hello` - `/hello/{name}` ### Request Body (Not applicable for GET, POST with path parameter) ### Request Example ```json # For POST /hello/{name} { "name": "Alice" } ``` ### Response #### Success Response (200) - `message` (str) - A greeting message. #### Response Example ```json { "message": "Hello, Alice" } ``` ``` -------------------------------- ### APIView Path Parameters Source: https://bolt.farhana.li/topics/class-based-views Handle path parameters in your APIView methods. This example shows how to accept and use a 'user_id' path parameter for GET and PUT requests. ```APIDOC ## APIView Path Parameters ### Description Handle path parameters in your `APIView` methods. This example shows how to accept and use a `user_id` path parameter for GET and PUT requests. ### Method GET, PUT ### Endpoint `/users/{user_id}` ### Parameters #### Path Parameters - **user_id** (int) - Required - The ID of the user. #### Request Body - **data** (UserUpdate) - Required - The update data for the user (for PUT requests). ### Request Example ```json # For PUT /users/123 { "field1": "value1", "field2": "value2" } ``` ### Response #### Success Response (200) - `user_id` (int) - The ID of the user. - `updated` (bool) - Indicates if the update was successful. #### Response Example ```json { "user_id": 123, "updated": true } ``` ``` -------------------------------- ### Create a Basic API Endpoint with Django-Bolt Source: https://bolt.farhana.li/index This snippet illustrates the creation of a simple "Hello, World!" API endpoint using Django-Bolt's BoltAPI and decorator-based routing. ```python from django_bolt import BoltAPI api = BoltAPI() @api.get("/") async def hello(): return {"message": "Hello, World!"} ``` -------------------------------- ### Mounting Multiple API Instances Source: https://bolt.farhana.li/topics/routing Shows how to create multiple BoltAPI instances and mount them under different URL prefixes to organize routes, for example, by application. ```APIDOC ## Mounting Users API under /api/v1 ### Description This example demonstrates mounting a separate `BoltAPI` instance (defined in `users.api`) under a specific URL prefix (`/api/v1`) in the main application's API instance. ### Method N/A (Configuration) ### Endpoint /api/v1/* (Routes from `users_api` will be prefixed) ### Parameters ### Request Body ### Request Example ### Response #### Success Response (Accessing `/api/v1/users` will route to the `list_users` function defined in `users.api`) #### Response Example (Example for `GET /api/v1/users`) ```json { "users": [] } ``` ``` -------------------------------- ### Get Classified Mission Info API Source: https://bolt.farhana.li/getting-started/quickstart Retrieves classified information about a specific mission. Requires a valid 'X-Clearance-Level' header. ```APIDOC ## GET /missions/{mission_id}/classified ### Description Retrieves classified information about a specific mission. Requires a valid 'X-Clearance-Level' header. ### Method GET ### Endpoint /missions/{mission_id}/classified ### Parameters #### Path Parameters - **mission_id** (int) - Required - The unique identifier of the mission. #### Header Parameters - **X-Clearance-Level** (str) - Required - The clearance level for accessing classified data. Must be 'top-secret' or 'confidential'. ### Response #### Success Response (200) - **mission** (str) - The name of the mission. - **classified_data** (str) - The classified information related to the mission. - **clearance_verified** (str) - The clearance level that was verified. #### Response Example ```json { "mission": "Apollo 11", "classified_data": "Launch codes: APOLLO-7749-OMEGA", "clearance_verified": "top-secret" } ``` #### Error Response (403) - **detail** (str) - "Insufficient clearance level" #### Error Response (404) - **detail** (str) - "Mission {mission_id} not found" ``` -------------------------------- ### Complete Production Logging Setup in Python Source: https://bolt.farhana.li/topics/logging Sets up a comprehensive production logging configuration using Django-Bolt. It includes performance optimizations like sampling and minimum duration logging, path/status code skipping, request/response field customization, security obfuscation for headers and cookies, and options for body logging. ```python from django_bolt import BoltAPI from django_bolt.logging import LoggingConfig, create_logging_middleware api = BoltAPI() # Production logging config config = LoggingConfig( logger_name="myapp.api", # Performance: Don't log every request sample_rate=0.1, # Log 10% of successful requests min_duration_ms=100, # Only log requests > 100ms # Skip noisy paths skip_paths={"health", "/ready", "/metrics", "/favicon.ico"}, skip_status_codes={204, 304}, # Request logging request_log_fields={"method", "path", "client_ip", "user_agent"}, # Response logging response_log_fields={"status_code", "duration"}, # Security obfuscate_headers={"authorization", "cookie", "x-api-key"}, obfuscate_cookies={"sessionid", "csrftoken", "jwt"}, # Body logging (careful in production) log_request_body=False, ) middleware = create_logging_middleware( logger_name=config.logger_name, skip_paths=config.skip_paths, sample_rate=config.sample_rate, ) ``` -------------------------------- ### GET /dashboard Source: https://bolt.farhana.li/getting-started/quickstart Renders the mission dashboard using a Django template, displaying a list of recent missions with their names, statuses, and descriptions. ```APIDOC ## GET /dashboard ### Description Renders the mission dashboard using a Django template, displaying a list of recent missions with their names, statuses, and descriptions. ### Method GET ### Endpoint /dashboard ### Parameters None ### Request Body None ### Response #### Success Response (200) - **HTML content** - The rendered HTML page for the mission dashboard. #### Response Example ```html Mission Dashboard

Mission Dashboard

Total missions: {{ missions|length }}

{% for mission in missions %}
{{ mission.name }} {{ mission.status|upper }}

{{ mission.description|default:"No description" }}

{% empty %}

No missions found.

{% endfor %} ``` ``` -------------------------------- ### GET /status-page Source: https://bolt.farhana.li/getting-started/quickstart Serves an HTML status page for Mission Control, indicating that all systems are operational and providing a link to the API documentation. ```APIDOC ## GET /status-page ### Description Serves an HTML status page for Mission Control, indicating that all systems are operational and providing a link to the API documentation. ### Method GET ### Endpoint /status-page ### Parameters None ### Request Body None ### Response #### Success Response (200) - **HTML content** - The HTML structure for the status page. #### Response Example ```html Mission Control

MISSION CONTROL STATUS

All systems operational

Visit /docs for API documentation

``` ``` -------------------------------- ### Document API Endpoint with Summary and Description Source: https://bolt.farhana.li/topics/openapi Demonstrates how to document a GET endpoint with a summary, description, and tags. The docstring content is also included in the generated documentation. ```python @api.get( "/users/{user_id}", summary="Get a user", description="Retrieve a user by their unique ID.", tags=["users"] ) async def get_user(user_id: int): """ This docstring also appears in the documentation. Additional details about the endpoint can go here. """ return {"user_id": user_id} ``` -------------------------------- ### Get Mission Control Status (Python) Source: https://bolt.farhana.li/getting-started/quickstart Retrieves the current operational status of the mission control system. This endpoint is part of the status reporting functionality. ```python import os from fastapi import FastAPI, Query, Header, File, HTTPException from fastapi.responses import PlainText from typing import Annotated # Assuming Mission, MissionFilters, CreateMission, UpdateMission, Astronaut, NotFound are defined elsewhere # For demonstration, placeholder classes are used. class MissionFilters: def __init__(self, status: str = None, limit: int = 10): self.status = status self.limit = limit class Mission: objects = None # Placeholder for ORM DoesNotExist = Exception def __init__(self, id, name, status, launch_date=None, description=None, patch_image=None): self.id = id self.name = name self.status = status self.launch_date = launch_date self.description = description self.patch_image = patch_image async def __aiter__(self): # Placeholder for async iteration yield self async def aget(self, id): # Placeholder for async get if id == 1: # Example data return Mission(id=1, name='Apollo 11', status='completed', launch_date='1969-07-16', description='First moon landing') raise self.DoesNotExist async def asave(self): pass async def adelede(self): pass class CreateMission: def __init__(self, name: str, description: str, launch_date: str): self.name = name self.description = description self.launch_date = launch_date class UpdateMission: def __init__(self, name: str = None, status: str = None, description: str = None): self.name = name self.status = status self.description = description class Astronaut: objects = None # Placeholder for ORM def __init__(self, id, name, role, mission): self.id = id self.name = name self.role = role self.mission = mission class CreateAstronaut: def __init__(self, name: str, role: str): self.name = name self.role = role class NotFound(HTTPException): pass app = FastAPI() @app.get("/", tags=["status"]) async def mission_control_status(): return {"status": "operational", "message": "Mission Control Online"} ```