### Install KeyCDN Python Library Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Use pip to install the KeyCDN Python library. This command should be run in your terminal. ```bash pip install keycdn ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Install the library in editable mode with development extras, including dependencies required for testing. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install Testing Dependencies Manually Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Install pytest and related libraries directly if not using tox. This is an alternative method for setting up the testing environment. ```bash pip install pytest responses pytest-env ``` -------------------------------- ### Make GET Requests with KeyCDN API Client Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Use the `get` method to make authenticated HTTP GET requests to KeyCDN API endpoints. It returns parsed JSON responses or raises an HTTPError on failure. Examples include listing zones, retrieving a specific zone, purging a zone's cache, or purging specific URLs. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # List all zones zones = api.get('zones.json') print(zones) # {'status': 'success', 'description': 'zones', 'data': {'zones': [...]}} # Get a specific zone by ID zone = api.get('zones/12345.json') print(zone['data']['zone']['name']) # Purge the cache for a specific zone result = api.get('zones/purge/12345.json') if result['status'] == 'success': print('Cache purged successfully') # Purge specific URLs from a zone's cache result = api.get('zones/purgeurl/12345.json', { 'urls': ['https://cdn.example.com/image.png', 'https://cdn.example.com/style.css'] }) print(result) ``` -------------------------------- ### Run Tests with Pytest Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Execute the test suite using pytest after manually installing the necessary dependencies. Ensure your virtual environment is activated. ```bash pytest ``` -------------------------------- ### Make POST Requests with KeyCDN API Client Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Use the `post` method for creating or updating resources via authenticated HTTP POST requests. Parameters are sent as form data. Examples include creating a new zone or updating a zone's gzip setting. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Create a new zone result = api.post('zones.json', { 'name': 'myzone', 'type': 'pull', 'originurl': 'https://origin.example.com' }) print(result) # {'status': 'success', 'description': 'Zone has been created', 'data': {'zone': {...}}} # Update a zone's gzip setting result = api.post('zones/37861.json', {'gzip': 'enabled'}) if result['status'] == 'success': print('Zone updated successfully') else: print('Update failed:', result) ``` -------------------------------- ### Make PUT Requests with KeyCDN API Client Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Use the `put` method for full-replacement updates on resources via authenticated HTTP PUT requests. The example shows enabling SSL for a zone, including custom certificate and key. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Enable SSL for a zone result = api.put('zones/12345.json', { 'ssl': 'enabled', 'sslcert': 'custom', 'sslkey': '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----' }) print(result) # {'status': 'success', 'description': 'Zone has been updated', ...} ``` -------------------------------- ### Get all zones Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Retrieves a list of all zones associated with your KeyCDN account. ```APIDOC ## GET zones.json ### Description Retrieves a list of all zones. ### Method GET ### Endpoint /zones.json ### Request Example ```python api.get('zones.json') ``` ### Response #### Success Response (200) - zones (array) - List of zone objects. ``` -------------------------------- ### Retrieve All Zones Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Call the get method on the API client to fetch a list of all zones associated with your KeyCDN account. ```python api.get('zones.json') ``` -------------------------------- ### api.get(call, params={}) Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Sends an authenticated HTTP GET request to the specified KeyCDN API endpoint. Returns the parsed JSON response as a Python dictionary. Raises an `HTTPError` on failure. ```APIDOC ## `api.get(call, params={})` — Make a GET Request Sends an authenticated HTTP GET request to the specified KeyCDN API endpoint. Returns the parsed JSON response as a Python dictionary. Raises an `HTTPError` if the response status code indicates failure. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # List all zones zones = api.get('zones.json') print(zones) # {'status': 'success', 'description': 'zones', 'data': {'zones': [...]}} # Get a specific zone by ID zone = api.get('zones/12345.json') print(zone['data']['zone']['name']) # Purge the cache for a specific zone result = api.get('zones/purge/12345.json') if result['status'] == 'success': print('Cache purged successfully') # Purge specific URLs from a zone's cache result = api.get('zones/purgeurl/12345.json', { 'urls': ['https://cdn.example.com/image.png', 'https://cdn.example.com/style.css'] }) print(result) ``` ``` -------------------------------- ### Get a specific zone Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Retrieves details for a specific zone using its ID. ```APIDOC ## POST zones/.json ### Description Retrieves details for a specific zone. ### Method POST ### Endpoint /zones/.json ### Parameters #### Path Parameters - **zoneId** (string) - Required - The ID of the zone to retrieve. ### Request Example ```python api.post('zones/.json') ``` ### Response #### Success Response (200) - zone (object) - Details of the specified zone. ``` -------------------------------- ### Make DELETE Requests with KeyCDN API Client Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Use the `delete` method to remove resources via authenticated HTTP DELETE requests. Parameters are sent as JSON in the request body. Examples include deleting a zone by ID or deleting a specific zone alias. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Delete a zone by ID result = api.delete('zones/12345.json') if result['status'] == 'success': print('Zone deleted') # Delete a specific zone alias result = api.delete('zonealiases/67890.json') print(result) # {'status': 'success', 'description': 'Zone alias has been deleted'} ``` -------------------------------- ### Purge Zone Cache Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Call the get method with the zone ID to purge the cache for a specific zone. Replace '' with the relevant zone ID. ```python api.get('zones/purge/.json') ``` -------------------------------- ### Initialize KeyCDN API Client Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Import the library and create an API client instance using your KeyCDN API key. Replace '' with your actual key. ```python import keycdn ... api = keycdn.Api('') ``` -------------------------------- ### keycdn.Api(ApiKey, session=None) Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Initializes an instance of the KeyCDN API client. Requires your KeyCDN API key. An optional session parameter can be provided for custom request sessions. ```APIDOC ## `keycdn.Api(ApiKey, session=None)` — Initialize the API Client Creates an instance of the KeyCDN API client. The `ApiKey` parameter is your KeyCDN API key. An optional `session` parameter allows injecting a custom `requests`-compatible session, useful for testing or connection pooling. ```python import keycdn # Initialize with your API key api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Verify the key and endpoint are set correctly print(api.get_api_key()) # 'sk_prod_YOUR_API_KEY_HERE' print(api.get_endpoint()) # 'https://api.keycdn.com' # Optional: override the endpoint (e.g., for testing) api.set_endpoint('https://api.keycdn.com') ``` ``` -------------------------------- ### List Tox Environments Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md View the available test environments managed by tox. This helps in selecting specific environments for testing. ```bash tox --listenvs ``` -------------------------------- ### Initialize KeyCDN API Client Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Initialize the KeyCDN API client with your API key. You can optionally override the default endpoint or inject a custom requests session. ```python import keycdn # Initialize with your API key api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Verify the key and endpoint are set correctly print(api.get_api_key()) # 'sk_prod_YOUR_API_KEY_HERE' print(api.get_endpoint()) # 'https://api.keycdn.com' # Optional: override the endpoint (e.g., for testing) api.set_endpoint('https://api.keycdn.com') ``` -------------------------------- ### Rotate API Key Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Demonstrates how to rotate the API key used by the client without needing to re-instantiate the Api object. It also shows how to retrieve the currently set API key. ```APIDOC ## Rotate API Key This snippet shows how to change the API key dynamically. ```python import keycdn # Assuming 'api' is an existing Api instance # api = keycdn.Api('sk_prod_OLD_KEY') # Rotate to a new API key without creating a new instance api.set_api_key('sk_prod_NEW_KEY') print(api.get_api_key()) # Output: 'sk_prod_NEW_KEY' # Make a call with the updated key zones = api.get('zones.json') print(zones) ``` ``` -------------------------------- ### Run All Tests with Tox Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Execute the test suite across all configured Python versions using tox. This command ensures compatibility with different Python environments. ```bash tox ``` -------------------------------- ### Manage API Key on KeyCDN API Client Instance Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Use `set_api_key` and `get_api_key` to manage the API key on an existing client instance. This is useful for credential rotation or reusing the client object. ```python import keycdn api = keycdn.Api('sk_prod_OLD_KEY') ``` -------------------------------- ### api.set_api_key(ApiKey) / api.get_api_key() Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Getter and setter methods for managing the API key on an existing client instance. Useful for rotating credentials or reusing the client object. ```APIDOC ## `api.set_api_key(ApiKey)` / `api.get_api_key()` — Manage API Key Getter and setter for the API key on an existing client instance. Useful when rotating credentials or reusing the same client object across contexts. ```python import keycdn api = keycdn.Api('sk_prod_OLD_KEY') ``` ``` -------------------------------- ### api.post(call, params={}) Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Sends an authenticated HTTP POST request to create or update a resource. Parameters are sent as form data. Returns the parsed JSON response as a Python dictionary. ```APIDOC ## `api.post(call, params={})` — Make a POST Request Sends an authenticated HTTP POST request to create or update a resource at the specified KeyCDN API endpoint. Parameters are sent as form data in the request body. Returns the parsed JSON response as a Python dictionary. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Create a new zone result = api.post('zones.json', { 'name': 'myzone', 'type': 'pull', 'originurl': 'https://origin.example.com' }) print(result) # {'status': 'success', 'description': 'Zone has been created', 'data': {'zone': {...}}} # Update a zone's gzip setting result = api.post('zones/37861.json', {'gzip': 'enabled'}) if result['status'] == 'success': print('Zone updated successfully') else: print('Update failed:', result) ``` ``` -------------------------------- ### api.set_endpoint(endpoint) / api.get_endpoint() Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Manage the API base URL. This is useful for testing with mock servers or pointing to staging environments. ```APIDOC ## `api.set_endpoint(endpoint)` / `api.get_endpoint()` — Manage API Endpoint Getter and setter for the API base URL. Primarily useful for testing with a mock server or pointing to a staging environment. ```python import keycdn import responses # Use a custom endpoint for testing api = keycdn.Api('test_key') api.set_endpoint('https://mock.keycdn.test') print(api.get_endpoint()) # 'https://mock.keycdn.test' # Example test using the responses library to mock HTTP calls @responses.activate def test_get_zones(): responses.add( responses.GET, 'https://api.keycdn.com/zones.json', json={'status': 'success', 'data': {'zones': []}}, ) api = keycdn.Api('sk_test_secret') result = api.get('zones.json') assert result['status'] == 'success' assert result['data']['zones'] == [] ``` ``` -------------------------------- ### Set Custom API Endpoint Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Configure a custom API base URL, primarily for testing with mock servers or targeting staging environments. The default endpoint is 'https://api.keycdn.com'. ```python import keycdn import responses # Use a custom endpoint for testing api = keycdn.Api('test_key') api.set_endpoint('https://mock.keycdn.test') print(api.get_endpoint()) # 'https://mock.keycdn.test' ``` ```python # Example test using the responses library to mock HTTP calls @responses.activate def test_get_zones(): responses.add( responses.GET, 'https://api.keycdn.com/zones.json', json={'status': 'success', 'data': {'zones': []}}, ) api = keycdn.Api('sk_test_secret') result = api.get('zones.json') assert result['status'] == 'success' assert result['data']['zones'] == [] ``` -------------------------------- ### Error Handling Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Demonstrates how to handle potential errors during API calls, such as HTTP errors, connection issues, and timeouts, by wrapping calls in a try/except block. ```APIDOC ## Error Handling All HTTP errors from the KeyCDN API are raised as `requests.exceptions.HTTPError` via `raise_for_status()`. Wrap calls in a try/except block to handle failures gracefully. ```python import keycdn import requests api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') try: # Attempt to fetch a non-existent zone result = api.get('zones/99999.json') print(result) except requests.exceptions.HTTPError as e: print(f'API error: {e.response.status_code} - {e.response.text}') except requests.exceptions.ConnectionError: print('Failed to connect to KeyCDN API') except requests.exceptions.Timeout: print('Request timed out') ``` ``` -------------------------------- ### api.put(call, params={}) Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Sends an authenticated HTTP PUT request for full-replacement updates on resources. Returns the parsed JSON response as a Python dictionary. ```APIDOC ## `api.put(call, params={})` — Make a PUT Request Sends an authenticated HTTP PUT request to the specified KeyCDN API endpoint. Used for full-replacement updates on resources. Returns the parsed JSON response as a Python dictionary. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Enable SSL for a zone result = api.put('zones/12345.json', { 'ssl': 'enabled', 'sslcert': 'custom', 'sslkey': '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----' }) print(result) # {'status': 'success', 'description': 'Zone has been updated', ...} ``` ``` -------------------------------- ### Handle API Errors Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Implement try/except blocks to gracefully manage potential HTTP errors, connection issues, or timeouts when interacting with the KeyCDN API. All HTTP errors are raised as `requests.exceptions.HTTPError`. ```python import keycdn import requests api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') try: # Attempt to fetch a non-existent zone result = api.get('zones/99999.json') print(result) except requests.exceptions.HTTPError as e: print(f'API error: {e.response.status_code} - {e.response.text}') except requests.exceptions.ConnectionError: print('Failed to connect to KeyCDN API') except requests.exceptions.Timeout: print('Request timed out') ``` -------------------------------- ### Retrieve a Specific Zone Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Use the post method with the zone ID to retrieve details for a specific zone. Ensure you replace '' with the actual zone ID. ```python api.post('zones/.json') ``` -------------------------------- ### Rotate API Key Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Update the API key used by the client instance without needing to create a new object. Useful for dynamic key rotation. ```python api.set_api_key('sk_prod_NEW_KEY') print(api.get_api_key()) # 'sk_prod_NEW_KEY' ``` ```python # Make a call with the updated key zones = api.get('zones.json') print(zones) ``` -------------------------------- ### Run Tox Tests for a Specific Environment Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Execute tox tests for a particular Python version, such as Python 3.6, by specifying the environment name. ```bash tox -e py36 ``` -------------------------------- ### api.delete(call, params={}) Source: https://context7.com/keycdn/python-keycdn-api/llms.txt Sends an authenticated HTTP DELETE request to remove a resource. Parameters are sent as JSON in the request body. Returns the parsed JSON response as a Python dictionary. ```APIDOC ## `api.delete(call, params={})` — Make a DELETE Request Sends an authenticated HTTP DELETE request to remove a resource at the specified KeyCDN API endpoint. Parameters are sent as JSON in the request body. Returns the parsed JSON response as a Python dictionary. ```python import keycdn api = keycdn.Api('sk_prod_YOUR_API_KEY_HERE') # Delete a zone by ID result = api.delete('zones/12345.json') if result['status'] == 'success': print('Zone deleted') # Delete a specific zone alias result = api.delete('zonealiases/67890.json') print(result) # {'status': 'success', 'description': 'Zone alias has been deleted'} ``` ``` -------------------------------- ### Purge zone cache Source: https://github.com/keycdn/python-keycdn-api/blob/master/README.md Clears the cache for a specified zone. ```APIDOC ## GET zones/purge/.json ### Description Clears the cache for a specified zone. ### Method GET ### Endpoint /zones/purge/.json ### Parameters #### Path Parameters - **zoneId** (string) - Required - The ID of the zone whose cache should be purged. ### Request Example ```python api.get('zones/purge/.json') ``` ### Response #### Success Response (200) - status (string) - Indicates the success of the purge operation. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.