### Run Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/examples/README.md Command to run any of the example .py files. ```bash $ python examples/.py ``` -------------------------------- ### GET Requests Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Examples of making GET requests with query parameters and custom headers. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth # Simple GET response = session.get('https://api.example.com/users') # GET with query parameters response = session.get( 'https://api.example.com/users', params={ 'limit': 10, 'offset': 20, 'filter': 'active' } ) # GET with custom headers response = session.get( 'https://api.example.com/users', headers={'Accept': 'application/json'} ) ``` -------------------------------- ### make_signing_key Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuthHeaders.md Example of how to use the make_signing_key method. ```python headers = EdgeGridAuthHeaders( client_token='token', client_secret='secret=', access_token='access' ) key = headers.make_signing_key('20260525T12:34:56+0000') # key is a base64-encoded hash string ``` -------------------------------- ### Constructor Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuth.md Example of initializing EdgeGridAuth and making a signed GET request. ```python import requests from akamai.edgegrid import EdgeGridAuth session = requests.Session() session.auth = EdgeGridAuth( client_token='akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj', client_secret='C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN=', access_token='akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij' ) # Make signed request result = session.get('https://akab-host.luna.akamaiapis.net/api/v1/endpoint') ``` -------------------------------- ### Install from source Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/README.md Install the edgegrid-python authentication handler from sources. ```bash pip install . ``` -------------------------------- ### Install from PyPI Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/README.md Install the edgegrid-python authentication handler from PyPI. ```bash pip install edgegrid-python ``` -------------------------------- ### Constructor Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuthHeaders.md Example of how to instantiate EdgeGridAuthHeaders with custom headers_to_sign and max_body. ```python from akamai.edgegrid.edgegrid import EdgeGridAuthHeaders headers = EdgeGridAuthHeaders( client_token='token', client_secret='secret=', access_token='access', headers_to_sign=['x-custom-header'], max_body=262144 ) ``` -------------------------------- ### Complete EdgeRC Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md A comprehensive example of an EdgeRC file showing configurations for default, production, and a secure API requiring custom headers. ```ini # Default API credentials [default] client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij host = akab-default-host.luna.akamaiapis.net max_body = 131072 # Production environment (different credentials) [production] client_token = akab-prod-token-xxxxxxxxxxx client_secret = ProdSecretBase64EncodedString== access_token = akab-prod-access-token-xxxxxxxxx host = akab-prod-host.luna.akamaiapis.net max_body = 131072 # API requiring custom header signature [secure-api] client_token = akab-secure-token-xxxxxxxxxxxxx client_secret = SecureSecretBase64EncodedString== access_token = akab-secure-access-token-xxxxxx host = akab-secure-api.luna.akamaiapis.net headers_to_sign = X-Nonce,X-Timestamp max_body = 262144 ``` -------------------------------- ### NoOptionError Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of a NoOptionError when required credentials are missing from a section. ```python configparser.NoOptionError: No option 'client_token' in section 'default' ``` -------------------------------- ### Full Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeRc.md A comprehensive example showing how to load an .edgerc file, iterate through sections, retrieve various configuration options, and print them. ```python from akamai.edgegrid import EdgeRc edgerc = EdgeRc('~/.edgerc') # List all sections sections = edgerc.sections() # ['default', 'production', ...] for section in sections: # Get all options in section options = edgerc.options(section) token = edgerc.get(section, 'client_token') host = edgerc.get(section, 'host') max_body = edgerc.getint(section, 'max_body', fallback=131072) headers = edgerc.getlist(section, 'headers_to_sign') print(f"[{section}]") print(f" Token: {token}") print(f" Host: {host}") print(f" Max Body: {max_body}") print(f" Headers: {headers}") ``` -------------------------------- ### EdgeRc get() Method Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeRc.md Shows how to retrieve configuration values using the get() method, including using a fallback value. ```python edgerc = EdgeRc('~/.edgerc') # Get required credentials token = edgerc.get('default', 'client_token') secret = edgerc.get('default', 'client_secret') # With fallback host = edgerc.get('prod', 'host', fallback='default.example.com') ``` -------------------------------- ### optionxform method example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeRc.md Example showing how optionxform allows using both dash and underscore styles for configuration keys. ```python # Both of these work in .edgerc file: # max_body = 131072 # max-body = 131072 edgerc = EdgeRc('~/.edgerc') value1 = edgerc.get('default', 'max_body') # Works value2 = edgerc.get('default', 'max-body') # Also works, same value ``` -------------------------------- ### File Permissions Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Demonstrates how to create and set restricted permissions for the .edgerc file. ```bash # Create .edgerc with restricted permissions touch ~/.edgerc chmod 600 ~/.edgerc # Edit with your credentials nano ~/.edgerc # Verify permissions (should show rw-------) ls -la ~/.edgerc ``` -------------------------------- ### Install Dependencies Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/README.md Command to install project dependencies from a requirements file. ```bash pip install -r dev-requirements.txt ``` -------------------------------- ### FileNotFoundError Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of a FileNotFoundError when the .edgerc file is missing. ```python FileNotFoundError: [Errno 2] No such file or directory: '~/.edgerc' ``` -------------------------------- ### Example 1: Get User Profile Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Demonstrates how to get a user profile using the EdgeGrid authentication and requests library. ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc import requests edgerc = EdgeRc('~/.edgerc') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc) response = session.get( f"https://{edgerc.get('default', 'host')}/identity-management/v3/user-profile" ) print(response.json()) ``` -------------------------------- ### __call__ Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuth.md Example demonstrating how the __call__ method is invoked automatically when assigned to session.auth. ```python import requests from akamai.edgegrid import EdgeGridAuth auth = EdgeGridAuth( client_token='token', client_secret='secret', access_token='access' ) session = requests.Session() session.auth = auth # __call__ is invoked automatically on each request # Authorization header added automatically response = session.get('https://api.example.net/path') ``` -------------------------------- ### getlist method example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeRc.md Example demonstrating how to use the getlist method to retrieve custom headers to include in a signature. ```python edgerc = EdgeRc('~/.edgerc') # Get headers to include in signature headers = edgerc.getlist('default', 'headers_to_sign') # Returns: ['X-Custom1', 'X-Custom2'] or None ``` -------------------------------- ### IAM API - Get User Profile Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Example of fetching a user's profile information from the Akamai Identity Management API. ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc import requests import json edgerc = EdgeRc('~/.edgerc') section = 'default' baseurl = f"https://{edgerc.get(section, 'host')}" session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) path = '/identity-management/v3/user-profile' headers = {'Accept': 'application/json'} querystring = { 'actions': True, 'authGrants': True, 'notifications': True } result = session.get(f"{baseurl}{path}", headers=headers, params=querystring) print(f"Status: {result.status_code}") print(json.dumps(result.json(), indent=2)) ``` -------------------------------- ### configparser.NoOptionError Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/errors.md Illustrates catching a configparser.NoOptionError when a required configuration key is missing. ```python from akamai.edgegrid import EdgeGridAuth import configparser # .edgerc [default] section missing client_token try: auth = EdgeGridAuth.from_edgerc('~/.edgerc') except configparser.NoOptionError as e: print(f"Missing config key: {e}") # No option 'client_token' in section: 'default' ``` -------------------------------- ### host in Code (URL construction) Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to retrieve the host from an .edgerc file and construct a base URL. ```python from akamai.edgegrid import EdgeRc edgerc = EdgeRc('~/.edgerc') host = edgerc.get('default', 'host') baseurl = f'https://{host}' ``` -------------------------------- ### host in EdgeRC Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to specify the host in an .edgerc file. ```ini [default] host = akab-host123456.luna.akamaiapis.net ``` -------------------------------- ### PUT and PATCH Requests Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Example of making a PUT request to replace a resource. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth # PUT request (replace entire resource) response = session.put( 'https://api.example.com/users/123', json={ 'name': 'Jane Doe', 'email': 'jane@example.com', 'role': 'admin' } ) ``` -------------------------------- ### EdgeRc Constructor Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeRc.md Demonstrates how to initialize the EdgeRc reader and load credentials from both the default location and a custom path. ```python from akamai.edgegrid import EdgeRc # Load from home directory edgerc = EdgeRc('~/.edgerc') # Get credentials from default section token = edgerc.get('default', 'client_token') host = edgerc.get('default', 'host') # Load from custom path edgerc = EdgeRc('/etc/akamai/.edgerc') ``` -------------------------------- ### client_token in EdgeRC Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to specify the client_token in an .edgerc file. ```ini [default] client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj ``` -------------------------------- ### from_edgerc Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuth.md Example of loading credentials from an EdgeRC file and making a signed request. ```python import requests from akamai.edgegrid import EdgeGridAuth, EdgeRc # Load from EdgeRc instance edgerc = EdgeRc('~/.edgerc') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, 'default') # Or load directly from file path session.auth = EdgeGridAuth.from_edgerc('~/.edgerc', 'production') # Make request result = session.get('https://akab-host.luna.akamaiapis.net/api/v1/endpoint') ``` -------------------------------- ### ValueError Example for max_body Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of a ValueError when max_body is not a valid integer. ```python ValueError: invalid literal for int() with base 10: 'not_a_number' ``` -------------------------------- ### EdgeRC Section Headers Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to define credential sections in an .edgerc file. ```ini [default] ...credentials... [production] ...credentials... [staging] ...credentials... ``` -------------------------------- ### Installation Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Install the edgegrid-python library using pip or from source. ```bash # From PyPI pip install edgegrid-python # From source git clone https://github.com/akamai/AkamaiOPEN-edgegrid-python.git cd AkamaiOPEN-edgegrid-python pip install . ``` -------------------------------- ### Request Body Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/README.md Example of how to construct and send a request body using EdgeGridAuth and requests. ```python edgerc = EdgeRc('~/.edgerc') section = 'default' baseurl = 'https://%s' % edgerc.get(section, 'host') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) path = '/identity-management/v3/user-profile/basic-info' payload = { "contactType": "Billing", "country": "USA", "firstName": "John", "lastName": "Smith", "preferredLanguage": "English", "sessionTimeOut": 30, "timeZone": "GMT", "phone": "3456788765" } result = session.put(urljoin(baseurl, path), json=payload) ``` -------------------------------- ### access_token in EdgeRC Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to specify the access_token in an .edgerc file. ```ini [default] access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij ``` -------------------------------- ### client_token in Code Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to pass the client_token directly to the EdgeGridAuth constructor. ```python auth = EdgeGridAuth( client_token='akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj', ... ) ``` -------------------------------- ### Example of io.UnsupportedOperation Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/errors.md Demonstrates how to catch and handle the io.UnsupportedOperation exception when dealing with non-seekable streams like pipes. ```python import io import os from akamai.edgegrid.edgegrid import read_stream_and_rewind # Pipe is not seekable r, w = os.pipe() os.write(w, b'data') os.close(w) try: with open(r, 'rb') as pipe: read_stream_and_rewind(pipe, 1024) except io.UnsupportedOperation as e: print(f"Stream not seekable: {e}") ``` -------------------------------- ### access_token in Code Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to pass the access_token directly to the EdgeGridAuth constructor. ```python auth = EdgeGridAuth( access_token='akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij', ... ) ``` -------------------------------- ### FileNotFoundError Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/errors.md An example of catching a FileNotFoundError when the .edgerc file does not exist. ```python from akamai.edgegrid import EdgeRc try: edgerc = EdgeRc('/nonexistent/path/.edgerc') except FileNotFoundError as e: print(f"Config file not found: {e}") # [Errno 2] No such file or directory: '/nonexistent/path/.edgerc' ``` -------------------------------- ### DELETE Requests Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Examples of making DELETE requests, with and without query parameters. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth # DELETE resource response = session.delete( 'https://api.example.com/users/123' ) # DELETE with query parameters response = session.delete( 'https://api.example.com/users', params={'confirm': 'true'} ) ``` -------------------------------- ### Pattern 1: Load Credentials from .edgerc Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md The most common setup pattern. Credentials are stored in .edgerc file in the user's home directory. ```python import requests from akamai.edgegrid import EdgeGridAuth, EdgeRc from urllib.parse import urljoin # Load configuration edgerc = EdgeRc('~/.edgerc') section = 'default' # Extract base URL from config baseurl = f"https://{edgerc.get(section, 'host')}" # Create authenticated session session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) # Make authenticated request response = session.get(f"{baseurl}/identity-management/v3/user-profile") print(response.status_code) print(response.json()) ``` -------------------------------- ### Example 2: Create API Credentials Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Shows how to create API credentials using the EdgeGrid authentication and requests library. ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc import requests edgerc = EdgeRc('~/.edgerc') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc) response = session.post( f"https://{edgerc.get('default', 'host')}/identity-management/v3/api-clients/self/credentials", json={'name': 'New API Client'} ) print(response.json()) ``` -------------------------------- ### make_auth_header example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuthHeaders.md Demonstrates how to use the make_auth_header method to generate a signed Authorization header for an HTTP request. ```python import requests from akamai.edgegrid.edgegrid import EdgeGridAuthHeaders, eg_timestamp, new_nonce headers = EdgeGridAuthHeaders( client_token='token', client_secret='secret=', access_token='access' ) req = requests.Request( method='GET', url='https://api.example.com/v1/resource' ).prepare() auth_value = headers.make_auth_header( req, eg_timestamp(), new_nonce() ) # Use in request req.headers['Authorization'] = auth_value ``` -------------------------------- ### POST Requests Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Examples of making POST requests with JSON body, form data, raw string body, file upload, and multipart form data. ```python from akamai.edgegrid import EdgeGridAuth import requests import json auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth # POST with JSON body response = session.post( 'https://api.example.com/users', json={'name': 'John Doe', 'email': 'john@example.com'} ) # POST with form data response = session.post( 'https://api.example.com/users', data={'name': 'John Doe'} ) # POST with raw string body response = session.post( 'https://api.example.com/config', data='raw-config-content', headers={'Content-Type': 'text/plain'} ) # POST with file with open('data.json', 'rb') as f: response = session.post( 'https://api.example.com/upload', data=f ) # POST with multipart form data from requests_toolbelt import MultipartEncoder fields = { 'file': ('document.pdf', open('document.pdf', 'rb')), 'title': 'My Document' } encoder = MultipartEncoder(fields=fields) response = session.post( 'https://api.example.com/upload', data=encoder, headers={'Content-Type': encoder.content_type} ) ``` -------------------------------- ### IAM API - Create Credentials Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Example of creating new API client credentials using the Akamai Identity Management API. ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc import requests import json edgerc = EdgeRc('~/.edgerc') section = 'default' baseurl = f"https://{edgerc.get(section, 'host')}" session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc, section) path = '/identity-management/v3/api-clients/self/credentials' payload = { 'name': 'New API Client', 'description': 'Created via API' } result = session.post(f"{baseurl}{path}", json=payload) print(f"Status: {result.status_code}") print(json.dumps(result.json(), indent=2)) ``` -------------------------------- ### Example usage of read_stream_and_rewind with different stream types Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/helper_functions.md Demonstrates how to use `read_stream_and_rewind` with a file object, BytesIO, and MultipartEncoder. ```python from akamai.edgegrid.edgegrid import read_stream_and_rewind import io # File object with open('data.json', 'rb') as f: content = read_stream_and_rewind(f, 1024) # file position is back at start file_again = f.read() # Can read full file # BytesIO stream = io.BytesIO(b'test data') content = read_stream_and_rewind(stream, 10) # b'test data' pos = stream.tell() # pos is 0 (rewound) # MultipartEncoder from requests_toolbelt import MultipartEncoder encoder = MultipartEncoder({'field': 'value'}) content = read_stream_and_rewind(encoder, 1024) # encoder is rewound for subsequent reads ``` -------------------------------- ### Internal Usage Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuthHeaders.md Shows how to access the internal EdgeGridAuthHeaders instance from an EdgeGridAuth object. ```python from akamai.edgegrid import EdgeGridAuth auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) # Access internal header preparation object headers_obj = auth.ah # Debug: inspect configuration print(headers_obj.client_token) print(headers_obj.headers_to_sign) print(headers_obj.max_body) ``` -------------------------------- ### max_body in Code Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to pass the max_body option directly to the EdgeGridAuth constructor. ```python auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access', max_body=262144 # 256 KB ) ``` -------------------------------- ### max_body in EdgeRC (dash) Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to specify the max_body option in an .edgerc file using a dash. ```ini [default] max-body = 262144 ``` -------------------------------- ### Workflow 4: Multiple Environments Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Example of loading authentication for different environments from .edgerc. ```python auth = EdgeGridAuth.from_edgerc('~/.edgerc', environment) # where environment is 'default', 'production', 'staging', etc. ``` -------------------------------- ### configparser.NoSectionError Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/errors.md Demonstrates catching a configparser.NoSectionError when a section is not found in the .edgerc file. ```python from akamai.edgegrid import EdgeGridAuth # .edgerc has [default] and [production] sections try: auth = EdgeGridAuth.from_edgerc('~/.edgerc', 'nonexistent') except Exception as e: print(type(e)) # configparser.NoSectionError print(e) # No section: 'nonexistent' ``` -------------------------------- ### headers_to_sign in EdgeRC (with spaces) Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of specifying custom headers to sign in the EdgeRC file, allowing for spaces after commas. ```ini [default] headers_to_sign = X-Custom-Header, X-Another-Header ``` -------------------------------- ### handle_redirect Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuth.md Demonstrates how `EdgeGridAuth` automatically handles HTTP redirects by re-signing the request for the new location, ensuring continued authentication. ```python # Automatic redirect handling session = requests.Session() session.auth = EdgeGridAuth( client_token='token', client_secret='secret', access_token='access' ) # If API returns 301/302, the redirected request is automatically re-signed response = session.get('https://api.example.net/old-path', allow_redirects=True) ``` -------------------------------- ### max_body in EdgeRC (underscore) Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to specify the max_body option in an .edgerc file using an underscore. ```ini [default] max_body = 131072 ``` -------------------------------- ### Example usage of determine_body_len with different body types Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/helper_functions.md Illustrates how to use `determine_body_len` with strings, bytes, and file objects. ```python from akamai.edgegrid.edgegrid import determine_body_len # String len1 = determine_body_len('Hello') # 5 # Bytes len2 = determine_body_len(b'Hello World') # 11 # File with open('data.json', 'rb') as f: len3 = determine_body_len(f) # File size in bytes # UTF-8 string len4 = determine_body_len('こんにちは') # 5 characters # 15 (5 chars × 3 bytes per char in UTF-8) ``` -------------------------------- ### PATCH Request (Partial Update) Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Example of performing a partial update on a resource using the PATCH method. ```python response = session.patch( 'https://api.example.com/users/123', json={'role': 'user'} ) ``` -------------------------------- ### Load Credentials from .edgerc Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Example of a .edgerc file with Akamai credentials. ```ini [default] client_token = akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= access_token = akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij host = akab-host123456.luna.akamaiapis.net ``` -------------------------------- ### get_header_versions example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuthHeaders.md Illustrates how to use the get_header_versions method to augment or create a User-Agent header with Akamai CLI version information. ```python from akamai.edgegrid.edgegrid import EdgeGridAuthHeaders import os # Without environment variables result = EdgeGridAuthHeaders.get_header_versions() # {'User-Agent': ''} or {} depending on implementation # With CLI version os.environ['AKAMAI_CLI'] = 'my-cli' os.environ['AKAMAI_CLI_VERSION'] = '1.2.3' result = EdgeGridAuthHeaders.get_header_versions() # {'User-Agent': 'AkamaiCLI/1.2.3'} # With existing User-Agent result = EdgeGridAuthHeaders.get_header_versions({'User-Agent': 'MyApp/1.0'}) # {'User-Agent': 'MyApp/1.0 AkamaiCLI/1.2.3'} ``` -------------------------------- ### headers_to_sign in Code Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of setting custom headers to sign directly within the EdgeGridAuth constructor in Python. ```python auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access', headers_to_sign=['X-Custom-Header', 'X-Another-Header'] ) ``` -------------------------------- ### Workflow 1: GET Request Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Example of making a GET request using EdgeGrid authentication loaded from .edgerc. ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc import requests edgerc = EdgeRc('~/.edgerc') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc) response = session.get( f"https://{edgerc.get('default', 'host')}/api/v1/users" ) ``` -------------------------------- ### Logging Configuration Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/MODULE_STRUCTURE.md Provides an example of how to configure logging for the akamai.edgegrid library using Python's standard logging module. ```python import logging logger = logging.getLogger('akamai.edgegrid') logger.setLevel(logging.DEBUG) # Or set root logger logging.basicConfig(level=logging.DEBUG) ``` -------------------------------- ### Example 3: With Error Handling Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Illustrates how to use EdgeGrid authentication with error handling for common exceptions. ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc import requests import configparser try: edgerc = EdgeRc('~/.edgerc') session = requests.Session() session.auth = EdgeGridAuth.from_edgerc(edgerc) response = session.get( f"https://{edgerc.get('default', 'host')}/api/v1/endpoint", timeout=10 ) response.raise_for_status() print(response.json()) except FileNotFoundError: print("Error: .edgerc file not found") except configparser.NoOptionError: print("Error: Missing credentials in .edgerc") except requests.exceptions.RequestException as e: print(f"Error: {e}") ``` -------------------------------- ### Example of requests.exceptions.RequestException Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/errors.md Illustrates how to handle various exceptions from the requests library, including timeouts, connection errors, and HTTP errors, when interacting with the Akamai API. ```python import requests from akamai.edgegrid import EdgeGridAuth auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth try: response = session.get('https://api.example.com/path', timeout=5) response.raise_for_status() # Raise HTTPError for 4xx/5xx except requests.exceptions.Timeout: print("Request timed out") except requests.exceptions.ConnectionError: print("Connection failed") except requests.exceptions.HTTPError as e: print(f"HTTP {e.response.status_code}: {e.response.text}") ``` -------------------------------- ### canonicalize_headers Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/api-reference/EdgeGridAuthHeaders.md Example demonstrating how canonicalize_headers formats request headers. ```python headers = EdgeGridAuthHeaders( client_token='token', client_secret='secret=', access_token='access', headers_to_sign=['X-Custom', 'X-Another'] ) request_headers = { 'Host': 'api.example.com', 'X-Custom': 'value1', 'X-Another': ' value2 ' } canonical = headers.canonicalize_headers(request_headers) # canonical = 'x-custom:value1 x-another:value2' ``` -------------------------------- ### Initialize Virtual Environment Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/README.md Commands to initialize a Python virtual environment on Unix/macOS and Windows. ```bash // Unix/macOS python3 -m venv ~/Desktop/myenv // Windows py -m venv ~/Desktop/myenv ``` -------------------------------- ### Prepared Requests Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to prepare a request object and then apply EdgeGrid authentication before sending it. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) # Prepare request req = requests.Request( 'GET', 'https://api.example.com/path', headers={'Accept': 'application/json'}, params={'limit': 10} ) prepared = req.prepare() # Apply authentication prepared = auth(prepared) # Send prepared request session = requests.Session() response = session.send(prepared) ``` -------------------------------- ### Working with Different Configuration Sections: Multiple Environments Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to load authentication credentials from different sections in the .edgerc file to manage multiple environments (e.g., development, production). ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc import requests import sys def get_auth(environment='default'): """Get authentication for specified environment.""" try: edgerc = EdgeRc('~/.edgerc') auth = EdgeGridAuth.from_edgerc(edgerc, environment) return auth, edgerc.get(environment, 'host') except Exception as e: print(f"Failed to load {environment} configuration: {e}", file=sys.stderr) sys.exit(1) # Use development credentials if '--dev' in sys.argv: auth, host = get_auth('development') elif '--prod' in sys.argv: auth, host = get_auth('production') else: auth, host = get_auth('default') session = requests.Session() session.auth = auth baseurl = f'https://{host}' ``` -------------------------------- ### Test Configuration Loading Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Illustrates how to test the loading of EdgeGrid configuration from a temporary .edgerc file. ```python import tempfile import os from akamai.edgegrid import EdgeRc, EdgeGridAuth def test_edgerc_loading(): # Create temporary .edgerc file with tempfile.NamedTemporaryFile(mode='w', suffix='.edgerc', delete=False) as f: f.write("""[test] client_token = test-token client_secret = test-secret= access_token = test-access host = test.example.com max_body = 262144 """) edgerc_path = f.name try: # Test loading edgerc = EdgeRc(edgerc_path) auth = EdgeGridAuth.from_edgerc(edgerc, 'test') assert auth.ah.client_token == 'test-token' assert auth.ah.client_secret == 'test-secret=' assert auth.ah.access_token == 'test-access' assert auth.ah.max_body == 262144 finally: os.unlink(edgerc_path) ``` -------------------------------- ### NoSectionError Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of a NoSectionError when a specified section is missing in the .edgerc file. ```python configparser.NoSectionError: No section: 'production' ``` -------------------------------- ### Working with Different Configuration Sections: Dynamic Section Selection Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to dynamically list and select available API configuration sections from the .edgerc file. ```python from akamai.edgegrid import EdgeRc, EdgeGridAuth import configparser edgerc = EdgeRc('~/.edgerc') # List available sections available_sections = edgerc.sections() print("Available API sections:") for section in available_sections: print(f" - {section}") ``` -------------------------------- ### configparser.ParsingError Example Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/errors.md Shows an example of catching a configparser.ParsingError when the .edgerc file has invalid INI syntax. ```python from akamai.edgegrid import EdgeRc import configparser # .edgerc has syntax error: [broken\nhost = example.com try: edgerc = EdgeRc('~/.edgerc') except configparser.ParsingError as e: print(f"Invalid .edgerc format: {e}") ``` -------------------------------- ### client_secret in EdgeRC Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to specify the client_secret in an .edgerc file. ```ini [default] client_secret = C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN= ``` -------------------------------- ### Common Usage: Load configuration with custom headers and make request Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Demonstrates loading EdgeGrid authentication from an EdgeRc file and making a request that includes custom headers. ```python # Load configuration with custom headers edgerc = EdgeRc('~/.edgerc') auth = EdgeGridAuth.from_edgerc(edgerc, 'api-section') # Make request with custom headers session = requests.Session() session.auth = auth response = session.get( 'https://api.example.com/v1/resource', headers={'X-Custom-Header': 'value'} ) ``` -------------------------------- ### client_secret in Code Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of how to pass the client_secret directly to the EdgeGridAuth constructor. ```python auth = EdgeGridAuth( client_secret='C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN=', ... ) ``` -------------------------------- ### Custom Request Logger Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Illustrates how to set up a custom logger to record request and response details, including URL, status, headers, and body. ```python import logging from akamai.edgegrid import EdgeGridAuth import requests logger = logging.getLogger('api_client') logging.basicConfig(level=logging.INFO) auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth # Log request and response details response = session.get('https://api.example.com/path') logger.info(f"URL: {response.url}") logger.info(f"Status: {response.status_code}") logger.info(f"Headers: {dict(response.headers)}") try: data = response.json() logger.info(f"Body: {data}") except: logger.info(f"Body: {response.text}") ``` -------------------------------- ### Batch Operations Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to process multiple resources efficiently by iterating through a list and making individual requests within a session. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth # Process multiple resources resources = ['resource1', 'resource2', 'resource3'] for resource in resources: try: response = session.get( f'https://api.example.com/resources/{resource}' ) response.raise_for_status() data = response.json() print(f"Processing {resource}: {data}") except requests.exceptions.RequestException as e: print(f"Failed to fetch {resource}: {e}") ``` -------------------------------- ### Custom Headers Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to add custom headers to requests, either for all requests within a session or for specific requests. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth # Add custom headers for all requests in session session.headers.update({ 'User-Agent': 'MyApp/1.0', 'Accept': 'application/json' }) response = session.get('https://api.example.com/path') # Or add headers to specific request response = session.get( 'https://api.example.com/path', headers={'X-Request-ID': 'unique-id-123'} ) ``` -------------------------------- ### Session Configuration Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Shows how to create and configure a `requests.Session` object with authentication, default headers, timeouts, and hooks for advanced usage. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) # Create configured session session = requests.Session() session.auth = auth # Add default headers session.headers.update({ 'User-Agent': 'MyApp/1.0', 'Accept': 'application/json' }) # Set default timeout session.timeout = 10 # Add hooks for logging def log_request(r, **kwargs): print(f"Sending request to {r.url}") return r session.hooks = {'response': log_request} # Use configured session response = session.get('https://api.example.com/path') ``` -------------------------------- ### Pattern 5: Environment Variables (CI/CD) Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Python code for initializing EdgeGridAuth using credentials provided via environment variables, common in CI/CD pipelines. ```python import os from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token=os.environ['AKAMAI_CLIENT_TOKEN'], client_secret=os.environ['AKAMAI_CLIENT_SECRET'], access_token=os.environ['AKAMAI_ACCESS_TOKEN'] ) session = requests.Session() session.auth = auth ``` -------------------------------- ### EdgeGridAuth Initialization Options Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/MODULE_STRUCTURE.md Demonstrates two ways to initialize EdgeGridAuth: from an .edgerc file or by providing direct credentials. ```python from akamai.edgegrid import EdgeGridAuth, EdgeRc edgerc = EdgeRc('~/.edgerc') auth = EdgeGridAuth.from_edgerc(edgerc, 'default') from akamai.edgegrid import EdgeGridAuth auth = EdgeGridAuth( client_token='...', client_secret='...', access_token='...' ) ``` -------------------------------- ### Optional Keys Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Example of optional keys for the .edgerc configuration file. ```ini [default] max_body = 131072 # Max POST body to hash headers_to_sign = X-Custom1,X-Custom2 # Headers in signature ``` -------------------------------- ### Required Keys Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Example of required keys for the .edgerc configuration file. ```ini [default] client_token = akab-... client_secret = ...= access_token = akab-... host = akab-....luna.akamaiapis.net ``` -------------------------------- ### Mock Authentication for Tests Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates how to mock the requests.Session.get method for testing API calls without making actual network requests. ```python import requests from unittest.mock import Mock, patch from akamai.edgegrid import EdgeGridAuth def test_api_call(): # Create mock response mock_response = Mock() mock_response.status_code = 200 mock_response.json.return_value = {'result': 'success'} # Mock session.get with patch('requests.Session.get', return_value=mock_response): auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth response = session.get('https://api.example.com/path') assert response.status_code == 200 assert response.json() == {'result': 'success'} ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Provides instructions on how to enable detailed debug logging for HTTP requests and specific loggers. ```python import logging from http.client import HTTPConnection # Configure root logger logging.basicConfig(level=logging.DEBUG) # Enable HTTP debugging HTTPConnection.debuglevel = 1 # Set specific loggers urllib_log = logging.getLogger("urllib3") urllib_log.setLevel(logging.DEBUG) urllib_log.propagate = True # Now make requests to see detailed debug output from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='token', client_secret='secret=', access_token='access' ) session = requests.Session() session.auth = auth response = session.get('https://api.example.com/path') ``` -------------------------------- ### Workflow 3: Error Handling Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Example of handling HTTP and request exceptions. ```python try: response = session.get(url) response.raise_for_status() except requests.exceptions.HTTPError as e: print(f"HTTP {e.response.status_code}") except requests.exceptions.RequestException as e: print(f"Request failed: {e}") ``` -------------------------------- ### Run Tests Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/README.md Commands to run tests using pytest on Unix/macOS and Windows. ```bash // Unix/macOS pytest -v // Windows py -m pytest -v ``` -------------------------------- ### Alternative: Direct Credentials Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/INDEX.md Example of using EdgeGridAuth with direct credential parameters. ```python from akamai.edgegrid import EdgeGridAuth import requests auth = EdgeGridAuth( client_token='akab-c113ntt0k3n4qtari252bfxxbsl-yvsdj', client_secret='C113nt53KR3TN6N90yVuAgICxIRwsObLi0E67/N8eRN=', access_token='akab-acc35t0k3nodujqunph3w7hzp7-gtm6ij' ) session = requests.Session() session.auth = auth response = session.get('https://akab-host123456.luna.akamaiapis.net/api/v1/endpoint') ``` -------------------------------- ### Error Handling: Basic Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/USAGE_PATTERNS.md Demonstrates basic error handling for requests, including file not found, configuration errors, timeouts, connection errors, HTTP errors, and invalid JSON responses. ```python import requests from akamai.edgegrid import EdgeGridAuth import configparser try: # Load configuration auth = EdgeGridAuth.from_edgerc('~/.edgerc', 'default') # Make request session = requests.Session() session.auth = auth response = session.get('https://api.example.com/path', timeout=10) # Check HTTP status response.raise_for_status() # Parse response data = response.json() except FileNotFoundError: print("Error: .edgerc file not found") except configparser.NoSectionError: print("Error: Section not found in .edgerc") except requests.exceptions.Timeout: print("Error: Request timed out") except requests.exceptions.ConnectionError: print("Error: Network connection failed") except requests.exceptions.HTTPError as e: print(f"Error: HTTP {e.response.status_code}") print(e.response.text) except ValueError: print("Error: Response is not valid JSON") ``` -------------------------------- ### headers_to_sign in EdgeRC (comma-separated) Source: https://github.com/akamai/akamaiopen-edgegrid-python/blob/master/_autodocs/configuration.md Example of specifying custom headers to sign in the EdgeRC file using a comma-separated format. ```ini [default] headers_to_sign = X-Custom-Header,X-Another-Header ```