### Install Development Environment with Pipx and Poetry Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Installs Pipx, ensures its path is set, and installs a specific version of Poetry for managing Python projects and dependencies. ```bash brew install pipx pipx ensurepath pipx install poetry==1.8.2 ``` -------------------------------- ### Create a Bunny CDN Pull Zone Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Illustrates the process of creating a new CDN pull zone using the Bunny SDK. This example includes setting essential parameters like name and origin URL, and demonstrates configuring optional settings for caching, security, and optimizations. ```python import asyncio from bunny_sdk import BunnySdk from bunny_sdk.bunny_api_client.models.pull_zone.pull_zone_create import PullZoneCreate async def create_pull_zone(): client = BunnySdk.create_bunny_api_client("your-api-key") # Create pull zone configuration new_zone = PullZoneCreate() new_zone.name = "my-cdn-zone" new_zone.origin_url = "https://myorigin.example.com" new_zone.type = 0 # Standard pull zone # Optional: Configure caching new_zone.cache_control_max_age_override = 3600 new_zone.cache_error_responses = True # Optional: Configure security new_zone.blocked_countries = ["CN", "RU"] new_zone.enable_geo_zone_a_f = True new_zone.enable_geo_zone_a_s = True new_zone.enable_geo_zone_e_u = True new_zone.enable_geo_zone_u_s = True # Optional: Enable optimizations new_zone.enable_smart_cache = True new_zone.enable_avif_vary = True new_zone.optimizer_enabled = True try: created_zone = await client.pullzone.post(new_zone) print(f"Pull zone created successfully!") print(f"ID: {created_zone.id}") print(f"Name: {created_zone.name}") print(f"CDN URL: {created_zone.cname_domain}") print(f"Monthly Bandwidth: {created_zone.monthly_bandwidth_used} bytes") return created_zone except Exception as e: print(f"Error creating pull zone: {e}") return None asyncio.run(create_pull_zone()) ``` -------------------------------- ### Install Project in Editable Mode Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Installs the current project in editable mode, allowing changes to be reflected immediately without reinstallation. ```bash pip install -e . ``` -------------------------------- ### Update Project Dependencies with Poetry Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Commands to update project dependencies, lock the current versions, install them, and activate the virtual environment. ```bash poetry update poetry lock poetry install source .venv/bin/activate ``` -------------------------------- ### GET /pullzone Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Retrieve all CDN pull zones with pagination support, filtering, and optional certificate information. ```APIDOC ## GET /pullzone ### Description Retrieve all CDN pull zones with pagination support, filtering, and optional certificate information. ### Method GET ### Endpoint /pullzone ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number to retrieve. - **per_page** (integer) - Optional - The number of items per page. - **search** (string) - Optional - A search term to filter pull zones by name. - **include_certificate** (boolean) - Optional - Whether to include certificate information in the response. ### Request Example ```python import asyncio from bunny_sdk import BunnySdk from kiota_abstractions.base_request_configuration import RequestConfiguration async def list_pull_zones(): client = BunnySdk.create_bunny_api_client("your-api-key") config = RequestConfiguration() config.query_parameters = { "page": 1, "per_page": 100, "search": "production", "include_certificate": True } try: response = await client.pullzone.get(config) if response and response.items: print(f"Total items: {response.total_items}") print(f"Current page: {response.current_page}") print(f"Has more: {response.has_more_items}") for zone in response.items: print(f"Zone ID: {zone.id}") print(f"Name: {zone.name}") print(f"Origin URL: {zone.origin_url}") print(f"CDN Domain: {zone.cname_domain}") print(f"Enabled: {zone.enabled}") print("---") except Exception as e: print(f"Error listing pull zones: {e}") asyncio.run(list_pull_zones()) ``` ### Response #### Success Response (200) - **total_items** (integer) - Total number of pull zones available. - **current_page** (integer) - The current page number. - **has_more_items** (boolean) - Indicates if there are more items to retrieve. - **items** (array) - A list of pull zone objects. - **id** (integer) - The unique identifier of the pull zone. - **name** (string) - The name of the pull zone. - **origin_url** (string) - The origin server URL. - **cname_domain** (string) - The CDN domain name. - **enabled** (boolean) - Indicates if the pull zone is enabled. #### Response Example ```json { "total_items": 1, "current_page": 1, "has_more_items": false, "items": [ { "id": 12345, "name": "my-production-zone", "origin_url": "https://myorigin.example.com", "cname_domain": "my-production-zone.b-cdn.net", "enabled": true } ] } ``` ``` -------------------------------- ### List Edge Scripts with Filtering in Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Retrieves a list of edge compute scripts with support for pagination and search functionality. This Python example utilizes request configuration to specify query parameters like page number, items per page, search terms, and whether to include linked pull zones. ```python import asyncio from bunny_sdk import BunnySdk from kiota_abstractions.base_request_configuration import RequestConfiguration async def list_edge_scripts(): client = BunnySdk.create_bunny_api_client("your-api-key") config = RequestConfiguration() config.query_parameters = { "page": 1, "per_page": 50, "search": "modifier", "include_linked_pull_zones": True } try: response = await client.compute.script.get(config) if response and response.items: for script in response.items: print(f"Script: {script.name}") print(f" ID: {script.id}") print(f" Type: {script.script_type}") print(f" Last Modified: {script.last_modified}") if script.linked_pull_zones: print(f" Linked Zones: {len(script.linked_pull_zones)}") print("---") except Exception as e: print(f"Error listing scripts: {e}") asyncio.run(list_edge_scripts()) ``` -------------------------------- ### Get User Account Information with Bunny SDK Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Retrieves current account details for a Bunny.net user, including billing information and service limits. Requires an API key for authentication. The output includes user ID, email, balance, bandwidth and storage usage, and service counts. Errors during the API call are caught and printed. ```python import asyncio from bunny_sdk import BunnySdk async def get_account_info(): client = BunnySdk.create_bunny_api_client("your-api-key") try: user = await client.user.get() print(f"Account Information:") print(f" ID: {user.id}") print(f" Email: {user.email}") print(f" Balance: ${user.balance:.2f}") print(f" Total Bandwidth Used: {user.total_bandwidth_used / (1024**4):.2f} TB") print(f" Storage Used: {user.total_storage_used / (1024**3):.2f} GB") print(f" Pull Zones: {user.pull_zone_count}") print(f" Storage Zones: {user.storage_zone_count}") print(f" Billing Type: {user.billing_type}") return user except Exception as e: print(f"Error getting account info: {e}") return None asyncio.run(get_account_info()) ``` -------------------------------- ### Get and Update Specific Pull Zone Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Retrieve a specific pull zone by its ID and update its configuration settings. This includes enabling smart cache, setting cache control, cookie vary, and allowed referrers. ```APIDOC ## GET /pullzone/{id} ### Description Retrieves the configuration details for a specific pull zone. ### Method GET ### Endpoint /pullzone/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the pull zone. ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pull zone. - **name** (string) - The name of the pull zone. - **enable_smart_cache** (boolean) - Indicates if smart caching is enabled. - **cache_control_max_age_override** (integer) - The cache control max age override in seconds. - **enable_cookie_vary** (boolean) - Indicates if cookie vary is enabled. - **allowed_referrers** (array of strings) - A list of allowed referrers. #### Response Example { "id": 12345, "name": "example-zone", "enable_smart_cache": false, "cache_control_max_age_override": 3600, "enable_cookie_vary": false, "allowed_referrers": [] } ## POST /pullzone/{id} ### Description Updates the configuration settings for a specific pull zone. ### Method POST ### Endpoint /pullzone/{id} ### Parameters #### Path Parameters - **id** (integer) - Required - The unique identifier of the pull zone. #### Request Body - **enable_smart_cache** (boolean) - Optional - Set to true to enable smart caching. - **cache_control_max_age_override** (integer) - Optional - Set the cache control max age override in seconds. - **enable_cookie_vary** (boolean) - Optional - Set to true to enable cookie vary. - **allowed_referrers** (array of strings) - Optional - A list of allowed referrers. ### Request Example { "enable_smart_cache": true, "cache_control_max_age_override": 7200, "enable_cookie_vary": true, "allowed_referrers": ["https://mysite.com", "https://www.mysite.com"] } ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the pull zone. - **name** (string) - The name of the pull zone. - **enable_smart_cache** (boolean) - Indicates if smart caching is enabled. - **cache_control_max_age_override** (integer) - The cache control max age override in seconds. - **enable_cookie_vary** (boolean) - Indicates if cookie vary is enabled. - **allowed_referrers** (array of strings) - A list of allowed referrers. #### Response Example { "id": 12345, "name": "example-zone", "enable_smart_cache": true, "cache_control_max_age_override": 7200, "enable_cookie_vary": true, "allowed_referrers": ["https://mysite.com", "https://www.mysite.com"] } ``` -------------------------------- ### Get Statistics with Date Range using Bunny SDK Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Fetches detailed statistics for bandwidth, requests, and cache performance over a specified date range, defaulting to the last 7 days. This function requires an API key and optionally accepts a pull zone ID and server zone ID. It outputs aggregated metrics and a daily breakdown of bandwidth usage. Error handling is included for API requests. ```python import asyncio from bunny_sdk import BunnySdk from datetime import datetime, timedelta from kiota_abstractions.base_request_configuration import RequestConfiguration async def get_statistics(): client = BunnySdk.create_bunny_api_client("your-api-key") # Calculate date range (last 7 days) end_date = datetime.now() start_date = end_date - timedelta(days=7) config = RequestConfiguration() config.query_parameters = { "dateFrom": start_date.strftime("%Y-%m-%d"), "dateTo": end_date.strftime("%Y-%m-%d"), "pullZone": 12345, # Optional: specific pull zone "serverZoneId": 0 # Optional: specific server zone } try: stats = await client.statistics.get(config) print(f"Statistics for {start_date.date()} to {end_date.date()}:") print(f" Total Bandwidth: {stats.total_bandwidth_used / (1024**3):.2f} GB") print(f" Total Requests: {stats.total_requests_served:,}") print(f" Cache Hit Rate: {stats.cache_hit_rate:.2f}%") print(f" Average Origin Response Time: {stats.average_origin_response_time:.2f}ms") if stats.bandwidth_used_chart: print("\nBandwidth by day:") for entry in stats.bandwidth_used_chart: print(f" {entry.date}: {entry.value / (1024**3):.2f} GB") return stats except Exception as e: print(f"Error getting statistics: {e}") return None asyncio.run(get_statistics()) ``` -------------------------------- ### Get and Update Specific Pull Zone Configuration Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Retrieves a specific pull zone by its ID and updates its configuration, including cache settings, TTL, and allowed referrers. It requires a valid API key and the zone ID. The function returns the updated pull zone object or None if an error occurs. ```python import asyncio from bunny_sdk import BunnySdk async def update_pull_zone_settings(zone_id: int): client = BunnySdk.create_bunny_api_client("your-api-key") try: # Get existing pull zone zone = await client.pullzone.by_id(zone_id).get() if zone: print(f"Current zone name: {zone.name}") print(f"Cache enabled: {zone.enable_smart_cache}") # Update settings zone.enable_smart_cache = True zone.cache_control_max_age_override = 7200 zone.enable_cookie_vary = True zone.allowed_referrers = ["https://mysite.com", "https://www.mysite.com"] # Save changes updated_zone = await client.pullzone.by_id(zone_id).post(zone) print(f"Pull zone updated successfully!") print(f"New cache setting: {updated_zone.enable_smart_cache}") return updated_zone except Exception as e: print(f"Error updating pull zone: {e}") return None asyncio.run(update_pull_zone_settings(12345)) ``` -------------------------------- ### Initialize Bunny SDK Clients Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Demonstrates how to create authenticated API clients for different Bunny.net services using the BunnySdk factory. It shows initialization for the main API client, edge storage client, stream client, and logging client, each requiring specific access keys and optional parameters like base URLs. ```python from bunny_sdk import BunnySdk # Create main API client for CDN management api_client = BunnySdk.create_bunny_api_client( access_key="your-api-key-here" ) # Create edge storage client for file operations storage_client = BunnySdk.create_edge_storage_api_client( access_key="your-storage-password", base_url="https://storage.bunnycdn.com" ) # Create stream client for video management stream_client = BunnySdk.create_stream_api_client( access_key="your-stream-api-key" ) # Create logging client for retrieving logs logging_client = BunnySdk.create_logging_api_client( access_key="your-api-key-here" ) ``` -------------------------------- ### Publish Package to PyPI Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Publishes the built package to the Python Package Index (PyPI) using Poetry. ```bash poetry publish ``` -------------------------------- ### Configure Poetry with PyPI Token Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Sets up Poetry to use a PyPI token for publishing packages. Replace '***' with your actual token. ```bash poetry config pypi-token.pypi *** ``` -------------------------------- ### Client Initialization - BunnySdk Factory Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Factory class for creating authenticated API clients with proper configuration and authentication providers for different Bunny.net services. ```APIDOC ## Client Initialization - BunnySdk Factory ### Description Factory class for creating authenticated API clients with proper configuration and authentication providers. ### Method Factory methods ### Endpoint N/A ### Parameters None ### Request Example ```python from bunny_sdk import BunnySdk # Create main API client for CDN management api_client = BunnySdk.create_bunny_api_client( access_key="your-api-key-here" ) # Create edge storage client for file operations storage_client = BunnySdk.create_edge_storage_api_client( access_key="your-storage-password", base_url="https://storage.bunnycdn.com" ) # Create stream client for video management stream_client = BunnySdk.create_stream_api_client( access_key="your-stream-api-key" ) # Create logging client for retrieving logs logging_client = BunnySdk.create_logging_api_client( access_key="your-api-key-here" ) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### POST /pullzone Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Create a new CDN pull zone with comprehensive configuration options including caching, security, and optimization settings. ```APIDOC ## POST /pullzone ### Description Create a new CDN pull zone with comprehensive configuration options including caching, security, and optimization settings. ### Method POST ### Endpoint /pullzone ### Parameters #### Request Body - **name** (string) - Required - The name of the new pull zone. - **origin_url** (string) - Required - The origin server URL for the pull zone. - **type** (integer) - Optional - The type of pull zone (e.g., 0 for standard). - **cache_control_max_age_override** (integer) - Optional - Custom Cache-Control max-age value in seconds. - **cache_error_responses** (boolean) - Optional - Whether to cache error responses. - **blocked_countries** (array of strings) - Optional - List of country codes to block access from. - **enable_geo_zone_a_f** (boolean) - Optional - Enable access from Africa. - **enable_geo_zone_a_s** (boolean) - Optional - Enable access from Asia. - **enable_geo_zone_e_u** (boolean) - Optional - Enable access from Europe. - **enable_geo_zone_u_s** (boolean) - Optional - Enable access from the United States. - **enable_smart_cache** (boolean) - Optional - Enable smart caching. - **enable_avif_vary** (boolean) - Optional - Enable AVIF Vary header. - **optimizer_enabled** (boolean) - Optional - Enable optimizer. ### Request Example ```python import asyncio from bunny_sdk import BunnySdk from bunny_sdk.bunny_api_client.models.pull_zone.pull_zone_create import PullZoneCreate async def create_pull_zone(): client = BunnySdk.create_bunny_api_client("your-api-key") new_zone = PullZoneCreate() new_zone.name = "my-cdn-zone" new_zone.origin_url = "https://myorigin.example.com" new_zone.type = 0 new_zone.cache_control_max_age_override = 3600 new_zone.cache_error_responses = True new_zone.blocked_countries = ["CN", "RU"] new_zone.enable_geo_zone_a_f = True new_zone.enable_geo_zone_a_s = True new_zone.enable_geo_zone_e_u = True new_zone.enable_geo_zone_u_s = True new_zone.enable_smart_cache = True new_zone.enable_avif_vary = True new_zone.optimizer_enabled = True try: created_zone = await client.pullzone.post(new_zone) print(f"Pull zone created successfully!") print(f"ID: {created_zone.id}") print(f"Name: {created_zone.name}") print(f"CDN URL: {created_zone.cname_domain}") print(f"Monthly Bandwidth: {created_zone.monthly_bandwidth_used} bytes") return created_zone except Exception as e: print(f"Error creating pull zone: {e}") return None asyncio.run(create_pull_zone()) ``` ### Response #### Success Response (200) - **id** (integer) - The unique identifier of the created pull zone. - **name** (string) - The name of the pull zone. - **cname_domain** (string) - The CDN domain name assigned to the pull zone. - **monthly_bandwidth_used** (integer) - The amount of bandwidth used in bytes for the current month. #### Response Example ```json { "id": 54321, "name": "my-cdn-zone", "cname_domain": "my-cdn-zone.b-cdn.net", "monthly_bandwidth_used": 0 } ``` ``` -------------------------------- ### Manage Package Version and Build Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Increments the package version, builds the distribution files (sdist and wheel), and stages all changes for commit. ```bash poetry version patch poetry build git add -A ``` -------------------------------- ### Create Edge Compute Script Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Creates and deploys edge compute scripts for serverless computing at the edge. Includes uploading script code and publishing. ```APIDOC ## POST /compute/script ### Description Creates a new edge compute script. After creation, the script code can be uploaded and the script published. ### Method POST ### Endpoint /compute/script ### Parameters #### Request Body - **name** (string) - Required - The name of the script. - **script_type** (int) - Required - The type of script (e.g., 0 for Standalone). ### Request Example ```json { "name": "request-modifier", "script_type": 0 } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created script. - **name** (string) - The name of the script. - **script_type** (int) - The type of the script. - **last_modified** (string) - The timestamp when the script was last modified. #### Response Example ```json { "id": "script-id-123", "name": "request-modifier", "script_type": 0, "last_modified": "2023-10-27T10:00:00Z" } ``` ## POST /compute/script/{script_id}/code ### Description Uploads the code for an existing edge compute script. ### Method POST ### Endpoint /compute/script/{script_id}/code ### Parameters #### Path Parameters - **script_id** (string) - Required - The ID of the script to upload code to. #### Request Body - **Code** (string) - Required - The actual script code. ### Request Example ```json { "Code": "addEventListener('fetch', event => { ... })" } ``` ### Response #### Success Response (200) - Typically returns an empty response or a success indicator. ## POST /compute/script/{script_id}/publish ### Description Publishes an edge compute script, making it active. ### Method POST ### Endpoint /compute/script/{script_id}/publish ### Parameters #### Path Parameters - **script_id** (string) - Required - The ID of the script to publish. ### Response #### Success Response (200) - Typically returns an empty response or a success indicator. ``` -------------------------------- ### Run Tests with Access Key Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Executes the main test script using `poetry run` and requires a BUNNY_ACCESS_KEY environment variable. ```bash BUNNY_ACCESS_KEY="***" poetry run python3 tests/main.py ``` -------------------------------- ### Create Storage Zone Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Create a new storage zone, which can optionally be configured with edge replication for distributed file storage and serving. ```APIDOC ## POST /storagezone ### Description Creates a new storage zone with specified region and optional edge replication. ### Method POST ### Endpoint /storagezone ### Parameters #### Request Body - **name** (string) - Required - The desired name for the storage zone. - **region** (string) - Required - The primary region for the storage zone (e.g., `DE`, `US`). Use enum values like `StandardRegions.DE`. - **replication_regions** (array of strings) - Optional - A list of regions for edge replication (e.g., `LA`, `SYD`). Use enum values like `EdgeReplicationRegions.LA`. - **zone_tier** (integer) - Optional - The tier of the storage zone. `0` for standard tier. ### Request Example { "name": "my-storage-zone", "region": "DE", "replication_regions": ["LA", "SYD"], "zone_tier": 0 } ### Response #### Success Response (201) - **id** (integer) - The unique identifier of the created storage zone. - **name** (string) - The name of the storage zone. - **region** (string) - The primary region of the storage zone. - **host_name** (string) - The hostname for accessing the storage zone. - **storage_used** (integer) - The amount of storage used in bytes. - **password** (string) - The password for the storage zone (handle securely). - **read_only_password** (string) - The read-only password for the storage zone. #### Response Example { "id": 98765, "name": "my-storage-zone", "region": "DE", "host_name": "storage.bunny.net/my-storage-zone", "storage_used": 10240, "password": "secure-password-here", "read_only_password": "readonly-password-here" } #### Error Response (400) - **message** (string) - "Invalid request payload or missing required fields." ``` -------------------------------- ### List Bunny CDN Pull Zones with Pagination Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Shows how to retrieve a list of CDN pull zones using the Bunny SDK with support for pagination, filtering, and including certificate information. It demonstrates setting query parameters and iterating through the response items, printing details for each zone. ```python import asyncio from bunny_sdk import BunnySdk from kiota_abstractions.base_request_configuration import RequestConfiguration async def list_pull_zones(): client = BunnySdk.create_bunny_api_client("your-api-key") # Configure query parameters config = RequestConfiguration() config.query_parameters = { "page": 1, "per_page": 100, "search": "production", "include_certificate": True } try: response = await client.pullzone.get(config) if response and response.items: print(f"Total items: {response.total_items}") print(f"Current page: {response.current_page}") print(f"Has more: {response.has_more_items}") for zone in response.items: print(f"Zone ID: {zone.id}") print(f"Name: {zone.name}") print(f"Origin URL: {zone.origin_url}") print(f"CDN Domain: {zone.cname_domain}") print(f"Enabled: {zone.enabled}") print("---") except Exception as e: print(f"Error listing pull zones: {e}") asyncio.run(list_pull_zones()) ``` -------------------------------- ### Create Edge Compute Script with Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Creates and deploys an edge compute script using the Bunny SDK. This involves defining the script's metadata, uploading its code, and publishing it. It requires an API key and returns the created script's details. ```python import asyncio from bunny_sdk import BunnySdk from bunny_sdk.bunny_api_client.models.compute.script_create import ScriptCreate async def create_edge_script(): client = BunnySdk.create_bunny_api_client("your-api-key") new_script = ScriptCreate() new_script.name = "request-modifier" new_script.script_type = 0 # Standalone script try: created_script = await client.compute.script.post(new_script) print(f"Edge script created!") print(f"ID: {created_script.id}") print(f"Name: {created_script.name}") # Upload script code script_code = """ addEventListener("fetch", event => { event.respondWith(handleRequest(event.request)) }) async function handleRequest(request) { // Add custom header let response = await fetch(request) let newResponse = new Response(response.body, response) newResponse.headers.set('X-Custom-Header', 'Processed-By-Bunny') return newResponse } """ code_body = {"Code": script_code} await client.compute.script.by_id(created_script.id).code.post(code_body) print("Script code uploaded!") # Publish script await client.compute.script.by_id(created_script.id).publish.post({}) print("Script published successfully!") return created_script except Exception as e: print(f"Error creating edge script: {e}") return None asyncio.run(create_edge_script()) ``` -------------------------------- ### Create Shield Zone (DDoS Protection) with Bunny SDK Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Configures DDoS protection and WAF rules for a specified pull zone to enhance security. This function requires an API key and the ID of the pull zone to secure. It allows customization of DDoS challenge window, sensitivity, learning mode, and plan type. The output confirms the creation of the shield zone and its basic settings. Error handling is included for the API call. ```python import asyncio from bunny_sdk import BunnySdk from bunny_sdk.bunny_api_client.models.shield.create_shield_zone_request import CreateShieldZoneRequest async def create_shield_zone(pull_zone_id: int): client = BunnySdk.create_bunny_api_client("your-api-key") shield_request = CreateShieldZoneRequest() shield_request.pull_zone_id = pull_zone_id shield_request.shield_zone_request = { "dDoSChallengeWindow": 0, "dDoSShieldSensitivity": 1, # Medium sensitivity "learningMode": False, "premiumPlan": True, "shieldZonePullZoneId": pull_zone_id } try: shield_zone = await client.shield.shield_zones.post(shield_request) print(f"Shield zone created!") print(f"Pull Zone ID: {shield_zone.shield_zone_pull_zone_id}") print(f"DDoS Protection: Enabled") print(f"WAF: Enabled") return shield_zone except Exception as e: print(f"Error creating shield zone: {e}") return None asyncio.run(create_shield_zone(12345)) ``` -------------------------------- ### Create Video Library (Stream) Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Creates a new video library for storing and managing video content within the Bunny Stream service. ```APIDOC ## POST /library ### Description Creates a new video library for managing video content. Allows specifying replication regions. ### Method POST ### Endpoint /library ### Parameters #### Request Body - **name** (string) - Required - The name of the video library. - **replication_regions** (array of strings) - Optional - An array of region codes (e.g., "DE", "NY") where the library content should be replicated. ### Request Example ```json { "name": "My Video Library", "replication_regions": ["DE", "NY", "LA", "SG"] } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created video library. - **name** (string) - The name of the video library. - **api_key** (string) - The API key for accessing the video library. - **video_library_hostname** (string) - The hostname for the video library's CDN. #### Response Example ```json { "id": "library-id-abc", "name": "My Video Library", "api_key": "your-stream-api-key", "video_library_hostname": "video-library-hostname.b-cdn.net" } ``` ``` -------------------------------- ### Create DNS Zone (Python) Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Creates a new DNS zone for domain management within the Bunny platform. It requires an API key for authentication and a domain name for the new zone. The function returns the details of the created zone, including its ID and nameservers, or indicates an error. ```python import asyncio from bunny_sdk import BunnySdk from bunny_sdk.bunny_api_client.models.dns_zone.dns_zone_create import DnsZoneCreate async def create_dns_zone(): client = BunnySdk.create_bunny_api_client("your-api-key") new_zone = DnsZoneCreate() new_zone.domain = "example.com" try: created_zone = await client.dnszone.post(new_zone) print(f"DNS Zone created!") print(f"ID: {created_zone.id}") print(f"Domain: {created_zone.domain}") print(f"Nameserver 1: {created_zone.nameserver1}") print(f"Nameserver 2: {created_zone.nameserver2}") return created_zone except Exception as e: print(f"Error creating DNS zone: {e}") return None asyncio.run(create_dns_zone()) ``` -------------------------------- ### List Edge Scripts with Filtering Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Retrieves a list of all edge compute scripts, with support for pagination, searching, and filtering. ```APIDOC ## GET /compute/script ### Description Retrieves a list of edge compute scripts with options for pagination, searching, and including linked pull zones. ### Method GET ### Endpoint /compute/script ### Parameters #### Query Parameters - **page** (int) - Optional - The page number for pagination (default is 1). - **per_page** (int) - Optional - The number of items per page (default is 50). - **search** (string) - Optional - A search term to filter scripts by name. - **include_linked_pull_zones** (boolean) - Optional - Whether to include information about linked pull zones. ### Response #### Success Response (200) - **items** (array) - An array of script objects. - **id** (string) - The unique identifier for the script. - **name** (string) - The name of the script. - **script_type** (int) - The type of the script. - **last_modified** (string) - The timestamp when the script was last modified. - **linked_pull_zones** (array) - Information about linked pull zones (if requested). #### Response Example ```json { "items": [ { "id": "script-id-123", "name": "request-modifier", "script_type": 0, "last_modified": "2023-10-27T10:00:00Z", "linked_pull_zones": [] } ] } ``` ``` -------------------------------- ### List Storage Zones with Filtering and Pagination (Python) Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Retrieves a list of storage zones with optional filtering by search term and pagination controls. It requires an API key for authentication and outputs details like zone name, ID, region, storage used, and file count. Errors during the API call are caught and printed. ```python import asyncio from bunny_sdk import BunnySdk from kiota_abstractions.base_request_configuration import RequestConfiguration async def list_storage_zones(): client = BunnySdk.create_bunny_api_client("your-api-key") config = RequestConfiguration() config.query_parameters = { "page": 1, "per_page": 50, "include_deleted": False, "search": "production" } try: response = await client.storagezone.get(config) if response and response.items: for zone in response.items: print(f"Storage Zone: {zone.name}") print(f" ID: {zone.id}") print(f" Region: {zone.region}") print(f" Used: {zone.storage_used / (1024**3):.2f} GB") print(f" Files: {zone.files_stored}") print("---") except Exception as e: print(f"Error listing storage zones: {e}") asyncio.run(list_storage_zones()) ``` -------------------------------- ### Create Video Library with Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Creates a new video library for video streaming and management using the Bunny SDK. This function requires a stream API key and allows specifying the library's name and replication regions. It outputs the details of the newly created library, including its ID, name, API key, and hostname. ```python import asyncio from bunny_sdk import BunnySdk async def create_video_library(): stream_client = BunnySdk.create_stream_api_client("your-stream-api-key") library_config = { "name": "My Video Library", "replication_regions": ["DE", "NY", "LA", "SG"] } try: created_library = await stream_client.library.post(library_config) print(f"Video library created!") print(f"ID: {created_library.id}") print(f"Name: {created_library.name}") print(f"API Key: {created_library.api_key}") print(f"CDN Hostname: {created_library.video_library_hostname}") return created_library except Exception as e: print(f"Error creating video library: {e}") return None asyncio.run(create_video_library()) ``` -------------------------------- ### Add DNS Records with Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Adds various types of DNS records (A, CNAME, TXT) to a specified zone using the Bunny SDK. It requires an API key and the zone ID as input. The function handles potential exceptions during the record creation process. ```python import asyncio from bunny_sdk import BunnySdk async def add_dns_record(zone_id: int): client = BunnySdk.create_bunny_api_client("your-api-key") # A record a_record = { "type": 0, # A record "name": "www", "value": "192.0.2.1", "ttl": 3600 } try: created_record = await client.dnszone.by_id(zone_id).records.post(a_record) print(f"DNS record created: {created_record.name}.{created_record.domain}") # CNAME record cname_record = { "type": 2, # CNAME "name": "cdn", "value": "cdn.example.com", "ttl": 3600 } await client.dnszone.by_id(zone_id).records.post(cname_record) # TXT record (for verification) txt_record = { "type": 3, # TXT "name": "_verification", "value": "verification-token-12345", "ttl": 3600 } await client.dnszone.by_id(zone_id).records.post(txt_record) print("All DNS records created successfully!") except Exception as e: print(f"Error adding DNS records: {e}") asyncio.run(add_dns_record(12345)) ``` -------------------------------- ### Create Custom WAF Rule with Bunny SDK Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Adds a custom Web Application Firewall (WAF) rule for advanced request filtering within a Shield Zone. This function requires an API key and the ID of the Shield Zone to which the rule will be applied. It allows specifying the rule's description, severity, action (e.g., block), and type (custom). The output confirms the rule creation and displays its ID and description. Error handling is included for the API call. ```python import asyncio from bunny_sdk import BunnySdk from bunny_sdk.bunny_api_client.models.shield.create_custom_waf_rule_request import CreateCustomWafRuleRequest from bunny_sdk.bunny_api_client.models.shield.create_custom_waf_rule_model import CreateCustomWafRuleModel async def create_waf_rule(shield_zone_id: int): client = BunnySdk.create_bunny_api_client("your-api-key") waf_rule = CreateCustomWafRuleModel() waf_rule.rule_description = "Block malicious user agents" waf_rule.rule_severity = 2 # High severity waf_rule.rule_action = 1 # Block waf_rule.rule_type = 0 # Custom request = CreateCustomWafRuleRequest() request.shield_zone_id = shield_zone_id request.waf_rule = waf_rule try: created_rule = await client.shield.waf.custom_rules.post(request) print(f"WAF rule created!") print(f"Rule ID: {created_rule.id}") print(f"Description: {created_rule.rule_description}") return created_rule except Exception as e: print(f"Error creating WAF rule: {e}") return None asyncio.run(create_waf_rule(12345)) ``` -------------------------------- ### Create New Storage Zone Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Creates a new storage zone with specified configurations, including name, region, optional edge replication regions, and zone tier. It requires a valid API key. The function returns the details of the newly created storage zone or None if an error occurs. Sensitive information like passwords should be handled securely. ```python import asyncio from bunny_sdk import BunnySdk from bunny_sdk.bunny_api_client.models.storage_zone.storage_zone_create import StorageZoneCreate from bunny_sdk.bunny_api_client.models.storage_zone.standard_regions import StandardRegions from bunny_sdk.bunny_api_client.models.storage_zone.edge_replication_regions import EdgeReplicationRegions async def create_storage_zone(): client = BunnySdk.create_bunny_api_client("your-api-key") # Create storage zone configuration new_storage = StorageZoneCreate() new_storage.name = "my-storage-zone" new_storage.region = StandardRegions.DE # Frankfurt region new_storage.replication_regions = [ EdgeReplicationRegions.LA, # Los Angeles EdgeReplicationRegions.SYD # Sydney ] new_storage.zone_tier = 0 # Standard tier try: created_storage = await client.storagezone.post(new_storage) print(f"Storage zone created!") print(f"ID: {created_storage.id}") print(f"Name: {created_storage.name}") print(f"Region: {created_storage.region}") print(f"Hostname: {created_storage.host_name}") print(f"Storage Used: {created_storage.storage_used} bytes") print(f"Password: {created_storage.password}") # Save this securely! print(f"Read-only Password: {created_storage.read_only_password}") return created_storage except Exception as e: print(f"Error creating storage zone: {e}") return None asyncio.run(create_storage_zone()) ``` -------------------------------- ### Download File from Edge Storage (Python) Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Downloads a file from a Bunny CDN Edge Storage zone to a local file path. It requires the storage zone name, the remote file path, and the desired local path for saving the downloaded content. The function provides feedback on success or failure. ```python import asyncio from bunny_sdk import BunnySdk async def download_file(storage_zone_name: str, remote_path: str, local_path: str): storage_client = BunnySdk.create_edge_storage_api_client( access_key="storage-zone-password", base_url=f"https://storage.bunnycdn.com" ) try: # Download file file_content = await storage_client.by_storage_zone_name(storage_zone_name).by_path(remote_path).get() # Save to local file with open(local_path, 'wb') as f: f.write(file_content) print(f"File downloaded successfully to {local_path}") except Exception as e: print(f"Error downloading file: {e}") asyncio.run(download_file("my-storage-zone", "images/logo.jpg", "/local/downloaded.jpg")) ``` -------------------------------- ### Perform Global Search with Bunny SDK Python Source: https://context7.com/jlarmstrongiv/bunny-sdk-python/llms.txt Searches across all Bunny resources including pull zones, storage zones, and scripts using a provided query. It utilizes the `BunnySdk` to interact with the search API and `RequestConfiguration` to specify search parameters and type. ```python import asyncio from bunny_sdk import BunnySdk from kiota_abstractions.base_request_configuration import RequestConfiguration async def global_search(query: str): client = BunnySdk.create_bunny_api_client("your-api-key") config = RequestConfiguration() config.query_parameters = { "search": query, "type": 0 # All types: 0=All, 1=PullZone, 2=StorageZone, 3=DNSZone } try: results = await client.search.get(config) if results and results.items: print(f"Found {len(results.items)} results for '{query}':") for item in results.items: print(f" Type: {item.type}") print(f" ID: {item.id}") print(f" Name: {item.name}") print(f" Description: {item.description}") print("---") else: print(f"No results found for '{query}'") return results except Exception as e: print(f"Error performing search: {e}") return None asyncio.run(global_search("production")) ``` -------------------------------- ### Commit and Push Changes Source: https://github.com/jlarmstrongiv/bunny-sdk-python/blob/main/CONTRIBUTING.md Commits staged changes with a provided message and pushes them to the remote repository. ```bash git commit -m "message" git push ```