### Full OAuthWebAuthCodeGrant Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Demonstrates the complete setup and usage of OAuthWebAuthCodeGrant for a web application. Includes creating the client, setting a token refresh callback, obtaining the authorization endpoint, requesting tokens, and creating AuthorizationData. ```python from bingads.authorization import ( AuthorizationData, OAuthWebAuthCodeGrant ) # Create OAuth client for web application auth = OAuthWebAuthCodeGrant( client_id='your_client_id', client_secret='your_client_secret', redirection_uri='https://your-domain.com/callback' ) # Define callback for token refresh def on_token_refreshed(tokens): # Store refreshed tokens in database save_tokens_to_db(tokens) auth.token_refreshed_callback = on_token_refreshed # Get authorization endpoint auth_endpoint = auth.get_authorization_endpoint() # After user grants consent: tokens = auth.request_oauth_tokens_by_response_uri(response_uri) # Create authorization data authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` -------------------------------- ### EntityUploadParameters Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-parameters.md Example demonstrating how to create EntityUploadParameters with a list of BulkCampaign entities and specify output file details and timeout. ```python from bingads.v13.bulk import EntityUploadParameters from bingads.v13.bulk.entities import BulkCampaign, BulkAdGroup # Create entities campaigns = [] for i in range(10): campaign = BulkCampaign() campaign.campaign.name = f'Campaign {i}' campaign.campaign.budget_type = 'DailyBudgetStandard' campaign.campaign.daily_budget = 50000 campaigns.append(campaign) # Create upload parameters upload_params = EntityUploadParameters( entities=campaigns, result_file_directory='/tmp', result_file_name='entity_upload_results.csv', response_mode='ErrorsAndResults', timeout_in_milliseconds=600000 ) ``` -------------------------------- ### Full Authorization Flow Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Demonstrates the complete OAuth desktop/mobile authorization code grant flow, including creating the client, getting the endpoint, requesting tokens, and setting up AuthorizationData for API calls. ```python from bingads.authorization import ( AuthorizationData, OAuthDesktopMobileAuthCodeGrant, OAuthTokens ) # Create OAuth client auth = OAuthDesktopMobileAuthCodeGrant(client_id='your_client_id') # Get authorization endpoint auth_endpoint = auth.get_authorization_endpoint() print(f"Navigate to: {auth_endpoint}") # After user grants consent and you receive response_uri: tokens = auth.request_oauth_tokens_by_response_uri(response_uri) # Use for API calls authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` -------------------------------- ### Google OAuth Desktop/Mobile Authentication Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Example of setting up Google OAuth for desktop or mobile applications. Retrieves the authorization endpoint. ```python from bingads.authorization import GoogleOAuthDesktopMobileAuthCodeGrant auth = GoogleOAuthDesktopMobileAuthCodeGrant( client_id='your_google_client_id' ) endpoint = auth.get_authorization_endpoint() ``` -------------------------------- ### Password Authentication Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Example of setting up legacy password authentication for Bing Ads. This method is deprecated. ```python from bingads.authorization import AuthorizationData, PasswordAuthentication auth = PasswordAuthentication(user_name='your_username', password='your_password') authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` -------------------------------- ### Install Bing Ads Python SDK Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/README.md Install the msads package using pip. This is the first step to using the SDK. ```bash pip install msads ``` -------------------------------- ### Basic Configuration Setup Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Set up the Configuration object for the API client, specifying the host URL and SSL verification. Adjust the timeout for longer-running requests. ```python from openapi_client.configuration import Configuration config = Configuration() config.host = 'https://api.ads.microsoft.com' config.verify_ssl = True config.timeout = 300 # 5 minutes ``` -------------------------------- ### BulkFileReader Examples Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Demonstrates reading different types of bulk files: full download, upload results, and partial/incremental downloads using context managers. ```python from bingads.v13.bulk import BulkFileReader, ResultFileType # Read a full download file with BulkFileReader('/tmp/campaigns.csv', result_file_type=ResultFileType.full_download) as reader: for entity in reader: if hasattr(entity, 'campaign_name'): print(f"Campaign: {entity.campaign_name}") elif hasattr(entity, 'ad_group_name'): print(f" AdGroup: {entity.ad_group_name}") # Read upload result file with BulkFileReader('/tmp/upload_result.csv', result_file_type=ResultFileType.upload) as reader: for entity in reader: if entity.errors: print(f"Errors: {entity.errors}") else: print(f"Success: {entity}") # Read partial/incremental download file with BulkFileReader('/tmp/incremental.csv', result_file_type=ResultFileType.partial_download) as reader: for entity in reader: print(f"Changed entity: {entity}") ``` -------------------------------- ### DownloadParameters Examples Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-parameters.md Demonstrates how to instantiate DownloadParameters for different download scenarios: full download, incremental download using last sync time, and downloading specific campaigns. ```python from bingads.v13.bulk import DownloadParameters from datetime import datetime, timedelta # Full download download_params = DownloadParameters( result_file_directory='/tmp', result_file_name='campaigns.csv', data_scope=['EntityData'], download_entities=['Campaign', 'AdGroup', 'TextAd'], file_type='Csv', timeout_in_milliseconds=600000 ) # Incremental download (only changes since last sync) last_sync_time = datetime.utcnow() - timedelta(days=1) incremental_params = DownloadParameters( result_file_directory='/tmp', result_file_name='incremental.csv', data_scope=['EntityData'], download_entities=['Campaign', 'AdGroup'], last_sync_time_in_utc=last_sync_time, timeout_in_milliseconds=600000 ) # Download specific campaigns only campaign_params = DownloadParameters( result_file_directory='/tmp', result_file_name='campaigns_subset.csv', campaign_ids=[123456, 234567, 345678], data_scope=['EntityData'], timeout_in_milliseconds=600000 ) ``` -------------------------------- ### OAuthTokens Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Demonstrates how to create and use an OAuthTokens object. ```APIDOC ## OAuthTokens Example ### Description Example usage of the OAuthTokens class. ### Code Example ```python from bingads.authorization import OAuthTokens tokens = OAuthTokens( access_token='access_token_value', access_token_expires_in_seconds=3600, refresh_token='refresh_token_value' ) if tokens.access_token_expired: print("Token has expired, refresh needed") ``` ``` -------------------------------- ### Example .env file for Bing Ads Configuration Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md This is an example of how to structure your .env file to store Bing Ads API credentials and configuration. Each line represents a key-value pair for an environment variable. ```dotenv BINGADS_CLIENT_ID=your_client_id BINGADS_CLIENT_SECRET=your_client_secret BINGADS_DEVELOPER_TOKEN=your_developer_token BINGADS_ACCOUNT_ID=1234567 BINGADS_CUSTOMER_ID=7654321 BINGADS_REDIRECT_URI=https://your-domain.com/callback BINGADS_ENVIRONMENT=production ``` -------------------------------- ### OAuthDesktopMobileImplicitGrant Usage Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Demonstrates how to instantiate OAuthDesktopMobileImplicitGrant, obtain the authorization endpoint, and extract access tokens from a redirect URI. ```python from bingads.authorization import OAuthDesktopMobileImplicitGrant auth = OAuthDesktopMobileImplicitGrant(client_id='your_client_id') # Get authorization endpoint endpoint = auth.get_authorization_endpoint() # User navigates to endpoint and is redirected with token in fragment # Extract token from the redirect URI tokens = auth.extract_access_token_from_uri(redirect_uri) ``` -------------------------------- ### FileUploadParameters Example: Upload with Compression Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-parameters.md Demonstrates how to configure FileUploadParameters for an upload with compression enabled, specifying result file details and a timeout. ```python from bingads.v13.bulk import FileUploadParameters # Upload with compression upload_params = FileUploadParameters( upload_file_path='/tmp/campaigns_to_upload.csv', result_file_directory='/tmp', result_file_name='upload_results.csv', compress_upload_file=True, response_mode='ErrorsAndResults', timeout_in_milliseconds=600000 ) ``` -------------------------------- ### Complete Bing Ads Python SDK Configuration and Operations Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md This snippet shows the full setup for using the Bing Ads Python SDK. It includes OAuth authentication, authorization data setup, BulkServiceManager configuration, and parameters for file download and upload operations. Ensure you replace placeholder values with your actual credentials and paths. The code also demonstrates how to refresh OAuth tokens if they have expired. ```python from datetime import datetime, timedelta from bingads.authorization import ( AuthorizationData, OAuthWebAuthCodeGrant, OAuthTokens ) from bingads.v13.bulk import ( BulkServiceManager, DownloadParameters, FileUploadParameters ) # Step 1: Set up OAuth authentication auth = OAuthWebAuthCodeGrant( client_id='your_app_client_id', client_secret='your_app_client_secret', redirection_uri='https://your-domain.com/oauth-callback', env='production', oauth_scope='msads.manage' ) # Step 2: Handle OAuth token flow # In a web application, redirect user to authorization endpoint auth_endpoint = auth.get_authorization_endpoint() # ... user grants permission and is redirected with authorization code ... # Parse response URI and get tokens tokens = auth.request_oauth_tokens_by_response_uri(response_uri) # Store tokens for later use saved_tokens = tokens # Step 3: Create authorization data authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='ABCDEFGHIJKLMNOPabcdefghijklmnop', authentication=auth ) # Step 4: Configure bulk service manager bulk_manager = BulkServiceManager( authorization_data=authorization_data, poll_interval_in_milliseconds=5000, environment='production', working_directory='/var/tmp/bingads' ) # Step 5: Configure download operation download_config = DownloadParameters( result_file_directory='/tmp/bingads', result_file_name='campaigns_export.csv', data_scope=['EntityData'], download_entities=['Campaign', 'AdGroup', 'TextAd'], timeout_in_milliseconds=600000 ) # Step 6: Configure upload operation upload_config = FileUploadParameters( upload_file_path='/tmp/campaigns_to_upload.csv', result_file_directory='/tmp/bingads', result_file_name='upload_results.csv', compress_upload_file=True, response_mode='ErrorsAndResults', timeout_in_milliseconds=600000 ) # Step 7: Refresh tokens if needed if tokens.access_token_expired: tokens = auth.request_oauth_tokens_by_refresh_token(tokens.refresh_token) # Step 8: Perform operations print("Starting bulk operations...") download_file = bulk_manager.download_file(download_config) print(f"Downloaded to: {download_file}") upload_result = bulk_manager.upload_file(upload_config) print(f"Upload results: {upload_result}") ``` -------------------------------- ### Writing Bulk Entities with BulkFileWriter Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Example demonstrating how to create and write campaign and ad group entities to a bulk file using BulkFileWriter within a context manager. ```python from bingads.v13.bulk import BulkFileWriter from bingads.v13.bulk.entities import BulkCampaign, BulkAdGroup from openapi_client.models.campaign import Campaign, AdGroup # Create and write entities with BulkFileWriter('/tmp/upload.csv') as writer: # Create a campaign campaign = BulkCampaign() campaign.campaign = Campaign() campaign.campaign.name = 'Test Campaign' campaign.campaign.budget_type = 'DailyBudgetStandard' campaign.campaign.daily_budget = 50000 writer.write_entity(campaign) # Create an ad group ad_group = BulkAdGroup() ad_group.ad_group = AdGroup() ad_group.ad_group.name = 'Test AdGroup' ad_group.campaign_name = 'Test Campaign' writer.write_entity(ad_group) ``` -------------------------------- ### Example Usage of UTCDateTime Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/types.md Demonstrates how to create a UTC datetime object representing 24 hours ago and use it to initialize DownloadParameters. ```python from datetime import datetime, timedelta # 24 hours ago last_sync = datetime.utcnow() - timedelta(days=1) download_params = DownloadParameters( last_sync_time_in_utc=last_sync ) ``` -------------------------------- ### BulkFileReader Example Usage Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Demonstrates how to use the BulkFileReader to read different types of bulk files (full download, upload results, partial download). ```APIDOC ### Example ```python from bingads.v13.bulk import BulkFileReader, ResultFileType # Read a full download file with BulkFileReader('/tmp/campaigns.csv', result_file_type=ResultFileType.full_download) as reader: for entity in reader: if hasattr(entity, 'campaign_name'): print(f"Campaign: {entity.campaign_name}") elif hasattr(entity, 'ad_group_name'): print(f" AdGroup: {entity.ad_group_name}") # Read upload result file with BulkFileReader('/tmp/upload_result.csv', result_file_type=ResultFileType.upload) as reader: for entity in reader: if entity.errors: print(f"Errors: {entity.errors}") else: print(f"Success: {entity}") # Read partial/incremental download file with BulkFileReader('/tmp/incremental.csv', result_file_type=ResultFileType.partial_download) as reader: for entity in reader: print(f"Changed entity: {entity}") ``` ``` -------------------------------- ### Example Progress Handler Function Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/types.md An example implementation of a progress handler function that prints the percentage complete and entities processed. This function can be passed to various BulkServiceManager methods or BulkOperation.track. ```python def progress_handler(progress_info): print(f"Progress: {progress_info.percentage_complete}%") print(f"Entities: {progress_info.entities_processed}") operation.track(progress_callback=progress_handler) ``` -------------------------------- ### Type Checking Example with Typing Module Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/types.md Provides an example of type checking using Python's `typing` module, including forward references for type hints. This is useful for static analysis and improving code clarity. ```python from typing import TYPE_CHECKING if TYPE_CHECKING: from bingads.v13.bulk import BulkEntity, BulkOperationProgressInfo from datetime import datetime def process_entities(entities: list['BulkEntity']) -> None: for entity in entities: pass def track_progress(progress: 'BulkOperationProgressInfo') -> None: print(f"Progress: {progress.percentage_complete}%") def set_last_sync(timestamp: 'datetime') -> None: pass ``` -------------------------------- ### Error Handling Example Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Illustrates how to handle potential API exceptions when using the ServiceClient. ```APIDOC ## Error Handling ### Description Calls to `ServiceClient` methods can raise exceptions defined in the `openapi_client.exceptions` module. This example shows how to catch and handle `ApiException`. ### Usage ```python from openapi_client.exceptions import ApiException from bingads.service_client import ServiceClient service_client = ServiceClient('Bulk', 13, authorization_data) try: response = service_client.download_campaigns_by_account_ids(request) except ApiException as e: print(f"API Error: {e.status}") print(f"Reason: {e.reason}") print(f"Body: {e.body}") ``` ### Common Exceptions - `ApiException`: General API error. - `ApiValueError`: Invalid parameter value. - `ApiTypeError`: Invalid parameter type. - Network exceptions for connectivity issues. ``` -------------------------------- ### FileUploadParameters Example: Upload without Compression Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-parameters.md Shows how to configure FileUploadParameters for an upload without compression, using a .zip extension for the result file which disables decompression. ```python # Upload without compression upload_params_no_compress = FileUploadParameters( upload_file_path='/tmp/large_campaigns.csv', result_file_directory='/tmp', result_file_name='results.zip', # .zip extension prevents decompression compress_upload_file=False, response_mode='ErrorsOnly', timeout_in_milliseconds=1200000 ) ``` -------------------------------- ### Direct Usage of ServiceClient - Bing Ads Python SDK Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Demonstrates direct instantiation and usage of the ServiceClient for making API calls, typically for the Bulk service. Ensure proper setup of authorization data and specify the service name, version, and environment. ```python from bingads.service_client import ServiceClient from bingads.authorization import AuthorizationData, OAuthWebAuthCodeGrant # Set up authorization auth = OAuthWebAuthCodeGrant(...) authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='token', authentication=auth ) # Create service client for bulk service service_client = ServiceClient( service_name='Bulk', version=13, authorization_data=authorization_data, environment='production' ) # Make API calls (normally done through BulkServiceManager) request = DownloadCampaignsByAccountIdsRequest( account_ids=[1234567], data_scope=['EntityData'], download_entities=['Campaign', 'AdGroup'] ) response = service_client.download_campaigns_by_account_ids( download_campaigns_by_account_ids_request=request ) # Get response headers headers = service_client.get_response_header() print(f"Request ID: {headers.get('RequestId')}") ``` -------------------------------- ### Handle FileDownloadException in Python Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/errors.md Shows how to catch and handle a FileDownloadException when downloading a file with the BulkServiceManager. This example requires valid authorization data and a specified result file directory. ```python from bingads.v13.bulk import BulkServiceManager, DownloadParameters from bingads.exceptions import FileDownloadException manager = BulkServiceManager(authorization_data) download_params = DownloadParameters(result_file_directory='/tmp') try: file_path = manager.download_file(download_params) except FileDownloadException as e: print(f"Download failed: {e.message}") ``` -------------------------------- ### Handle BulkDownloadException in Python Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/errors.md Catch and handle BulkDownloadException during bulk file downloads. This example shows how to retry the download with an increased timeout if the initial attempt fails. ```python from bingads.v13.bulk import BulkServiceManager, DownloadParameters from bingads.v13.bulk.exceptions import BulkDownloadException manager = BulkServiceManager(authorization_data) download_params = DownloadParameters(timeout_in_milliseconds=5000) try: file_path = manager.download_file(download_params) except BulkDownloadException as e: print(f"Download failed: {e.message}") # Implement retry with longer timeout download_params.timeout_in_milliseconds = 600000 file_path = manager.download_file(download_params) ``` -------------------------------- ### Handling TimeoutException in Python Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/errors.md This example shows how to catch a TimeoutException, which is raised when a Bing Ads SDK operation exceeds its specified timeout. It includes basic error reporting and suggests implementing retry logic. ```python from bingads.v13.bulk import BulkServiceManager from bingads.exceptions import TimeoutException manager = BulkServiceManager(authorization_data) # Assuming download_params is initialized elsewhere with timeout_in_milliseconds # download_params = DownloadParameters(timeout_in_milliseconds=10000) try: # file_path = manager.download_file(download_params) pass # Placeholder for actual download call except TimeoutException as e: print(f"Download timed out: {e.message}") # Implement retry or fallback logic ``` -------------------------------- ### Advanced ApiClient Configuration Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Configure the ApiClient with custom settings for host, SSL verification, connection pooling, and retries. This is useful for specific environment setups or advanced control. ```python from openapi_client.api_client import ApiClient from openapi_client.configuration import Configuration # Custom configuration config = Configuration() config.host = 'https://api.ads.microsoft.com' # Production config.verify_ssl = True config.connection_pool_maxsize = 10 config.retries = 3 client = ApiClient(config) ``` -------------------------------- ### Initialize Bulk Service Manager Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-service-manager.md Sets up authentication and creates an instance of the BulkServiceManager. Ensure you replace placeholders with your actual credentials and tokens. ```python from bingads.authorization import AuthorizationData, OAuthWebAuthCodeGrant from bingads.v13.bulk import ( BulkServiceManager, DownloadParameters, EntityUploadParameters ) from bingads.v13.bulk.entities import BulkCampaign # Set up authentication auth = OAuthWebAuthCodeGrant( client_id='your_client_id', client_secret='your_client_secret', redirection_uri='https://example.com/callback' ) # Get OAuth tokens first tokens = auth.request_oauth_tokens_by_response_uri(response_uri) authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) # Create bulk service manager manager = BulkServiceManager( authorization_data=authorization_data, poll_interval_in_milliseconds=5000 ) ``` -------------------------------- ### Configure Full Download Parameters Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Set up DownloadParameters for a full export, specifying directory, filename, data scope, entities, and timeout. ```python from bingads.v13.bulk import DownloadParameters download_params = DownloadParameters( result_file_directory='/tmp/bingads', result_file_name='full_export.csv', overwrite_result_file=True, data_scope=['EntityData'], download_entities=[ 'Account', 'Campaign', 'AdGroup', 'TextAd', 'Keyword', 'NegativeKeyword', 'CampaignNegativeKeyword', 'AdGroupNegativeKeyword' ], file_type='Csv', timeout_in_milliseconds=1200000 # 20 minutes ) ``` -------------------------------- ### BulkOperation Methods Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Provides methods to get the status, check completion, track progress, and download results of a bulk operation. ```APIDOC ## BulkOperation Base class for tracking bulk operation status and downloading results. ### Methods #### get_status() Gets the current status of the bulk operation. ```python def get_status() -> BulkOperationStatus: ``` **Returns:** BulkOperationStatus object **Example:** ```python operation = manager.submit_download(download_params) status = operation.get_status() print(f"Status: {status.status}") print(f"Progress: {status.percent_complete}%") ``` #### is_completed() Checks if the bulk operation has completed. ```python def is_completed() -> bool: ``` **Returns:** True if operation is completed, False otherwise #### track(progress_callback=None, timeout_in_milliseconds=None) Polls the service until the operation is completed. ```python def track(progress_callback=None, timeout_in_milliseconds=None): ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | progress_callback | callable | No | Optional callback function receiving BulkOperationProgressInfo | | timeout_in_milliseconds | int | No | Maximum time to wait for completion | **Throws:** TimeoutException if operation does not complete within timeout **Example:** ```python def progress_handler(progress_info): print(f"Progress: {progress_info.percentage_complete}%") operation = manager.submit_download(download_params) operation.track(progress_callback=progress_handler, timeout_in_milliseconds=600000) ``` #### download_result_file(result_file_directory=None, result_file_name=None, decompress=True, overwrite=False, timeout_in_milliseconds=None) Downloads the result file from the server. ```python def download_result_file(result_file_directory=None, result_file_name=None, decompress=True, overwrite=False, timeout_in_milliseconds=None) -> str: ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | result_file_directory | str | No | Directory to save the result file | | result_file_name | str | No | Name for the result file | | decompress | bool | No | Whether to decompress the file | | overwrite | bool | No | Whether to overwrite existing file | | timeout_in_milliseconds | int | No | Timeout for download | **Returns:** Path to the downloaded file (str) **Throws:** FileException, TimeoutException ### Example ```python operation = manager.submit_download(download_params) # Track progress def on_progress(progress_info): print(f"Download {progress_info.percentage_complete}% complete") operation.track(on_progress, timeout_in_milliseconds=600000) # Download result result_file = operation.download_result_file( result_file_directory='/tmp', result_file_name='campaigns.csv', decompress=True, overwrite=True, timeout_in_milliseconds=300000 ) print(f"Downloaded to: {result_file}") ``` ``` -------------------------------- ### Configure Campaign-Specific Download Parameters Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Set up DownloadParameters to download data for a specific list of campaign IDs. ```python download_params = DownloadParameters( result_file_directory='/tmp/bingads', campaign_ids=[123456, 234567, 345678], # Max 1,000 campaigns data_scope=['EntityData'], download_entities=['Campaign', 'AdGroup', 'TextAd', 'Keyword'], timeout_in_milliseconds=600000 ) ``` -------------------------------- ### Get Bulk Operation Status Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Retrieve the current status of a bulk operation. This includes the overall status and completion percentage. ```python operation = manager.submit_download(download_params) status = operation.get_status() print(f"Status: {status.status}") print(f"Progress: {status.percent_complete}%") ``` -------------------------------- ### Using BulkServiceManager vs. ServiceClient Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Illustrates the recommended approach using BulkServiceManager and the less recommended direct usage of ServiceClient for API communication. ```python # Recommended: Use BulkServiceManager from bingads.v13.bulk import BulkServiceManager, DownloadParameters manager = BulkServiceManager(authorization_data) file_path = manager.download_file(download_params) # Not recommended: Direct ServiceClient usage from bingads.service_client import ServiceClient client = ServiceClient('Bulk', 13, authorization_data) # ... manual request/response handling ... ``` -------------------------------- ### Get Authorization Endpoint Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Retrieves the Microsoft Account authorization endpoint URL. The user must navigate to this URL to grant consent. ```python def get_authorization_endpoint() -> str: ``` ```python auth = OAuthDesktopMobileAuthCodeGrant(client_id='your_client_id') endpoint = auth.get_authorization_endpoint() # User navigates to endpoint in browser ``` -------------------------------- ### Configure Incremental Download Parameters Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Set up DownloadParameters for incremental downloads, specifying a time range for changes and a shorter timeout. ```python from datetime import datetime, timedelta from bingads.v13.bulk import DownloadParameters # Download only changes from last 24 hours last_sync = datetime.utcnow() - timedelta(days=1) incremental_params = DownloadParameters( result_file_directory='/tmp/bingads', result_file_name='incremental_changes.csv', data_scope=['EntityData'], download_entities=['Campaign', 'AdGroup', 'TextAd'], last_sync_time_in_utc=last_sync, timeout_in_milliseconds=600000 # 10 minutes ) ``` -------------------------------- ### Get Response Header - ServiceClient Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Retrieves the HTTP headers from the last API response. Useful for obtaining tracking and request IDs. ```python def get_response_header() -> dict: ``` ```python response = service_client.submit_download(request) headers = service_client.get_response_header() tracking_id = headers.get('TrackingId') request_id = headers.get('RequestId') ``` -------------------------------- ### Initialize BulkServiceManager Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-service-manager.md Instantiate the BulkServiceManager with authorization data and optional parameters for polling interval, environment, working directory, location, and SUDS options. ```python from bingads.v13.bulk import BulkServiceManager, DownloadParameters manager = BulkServiceManager(authorization_data) ``` -------------------------------- ### Get Authorization Endpoint URL Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Retrieves the Microsoft Account authorization endpoint URL. This URL is used to redirect users to grant consent for your application. ```python def get_authorization_endpoint() -> str: ``` -------------------------------- ### ServiceClient Initialization Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Demonstrates how to initialize the ServiceClient for different Bing Ads APIs. ```APIDOC ## ServiceClient Initialization ### Description Initialize the `ServiceClient` to access specific Bing Ads APIs. The `service_name` parameter determines which API service is loaded. ### Usage ```python from bingads.service_client import ServiceClient # Bulk Service bulk_service = ServiceClient('Bulk', 13, authorization_data) # Campaign Management Service campaign_service = ServiceClient('CampaignManagement', 13, authorization_data) # Reporting Service reporting_service = ServiceClient('Reporting', 13, authorization_data) ``` ### Parameters - **service_name** (string) - The name of the API service (e.g., 'Bulk', 'CampaignManagement', 'Reporting'). - **api_version** (integer) - The API version number. - **authorization_data** - An object containing authorization credentials. ``` -------------------------------- ### Get Bulk Operation Status Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Retrieve the status, completion percentage, and request ID of a bulk operation. This is useful for monitoring the state of asynchronous tasks. ```python operation = manager.submit_download(download_params) status = operation.get_status() print(f"Status: {status.status}") print(f"Complete: {status.percent_complete}%") print(f"Request ID: {status.request_id}") ``` -------------------------------- ### Initialize Service Clients Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Instantiate ServiceClient for different Bing Ads APIs like Bulk, Campaign Management, and Reporting. Requires the service name, API version, and authorization data. ```python from bingads.service_client import ServiceClient # Bulk Service bulk_service = ServiceClient('Bulk', 13, authorization_data) # Campaign Management Service campaign_service = ServiceClient('CampaignManagement', 13, authorization_data) # Reporting Service reporting_service = ServiceClient('Reporting', 13, authorization_data) ``` -------------------------------- ### Set Up OAuth Web Authentication Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/README.md Configure OAuthWebAuthCodeGrant for authentication. You need to provide your client ID, client secret, and redirection URI. ```python from bingads.authorization import ( AuthorizationData, OAuthWebAuthCodeGrant ) # Create OAuth client auth = OAuthWebAuthCodeGrant( client_id='your_client_id', client_secret='your_client_secret', redirection_uri='https://your-domain.com/callback' ) # Get OAuth tokens tokens = auth.request_oauth_tokens_by_response_uri(response_uri) # Create authorization data authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` -------------------------------- ### BulkFileWriter Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Initializes the BulkFileWriter with a file path and optional encoding. The file path is required, while encoding defaults to 'utf-8-sig'. ```python def __init__(self, file_path, encoding='utf-8-sig'): ``` -------------------------------- ### DownloadParameters Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-parameters.md Defines the parameters for downloading files from the Bing Ads server. Use this to specify the directory, file name, data scope, entities, file type, campaign IDs, last sync time, and timeout for the download operation. ```python def __init__(self, result_file_directory=None, result_file_name=None, overwrite_result_file=False, data_scope=None, download_entities=None, file_type='Csv', campaign_ids=None, last_sync_time_in_utc=None, timeout_in_milliseconds=None): ``` -------------------------------- ### SubmitDownloadParameters Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-parameters.md Defines the parameters for a bulk download request, including data scope, entities, file type, specific campaign IDs, and last sync time. ```python def __init__(self, data_scope=None, download_entities=None, file_type='Csv', campaign_ids=None, last_sync_time_in_utc=None): ``` -------------------------------- ### Handle OperationError within BulkException Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/errors.md This example demonstrates how to catch a BulkException and iterate through its list of OperationError objects to display specific error details returned by a Bing Ads service operation. ```python from bingads.v13.bulk.exceptions import BulkException try: file_path = manager.download_file(download_params) except BulkException as e: for operation_error in e.errors: print(f"Code: {operation_error.code}") print(f"Error Code: {operation_error.error_code}") print(f"Message: {operation_error.message}") print(f"Details: {operation_error.details}") ``` -------------------------------- ### Handle EntityReadException in Python Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/errors.md Catch and handle EntityReadException when reading bulk entities from a CSV file. This example demonstrates accessing the error message, row values, and inner exception for debugging. ```python from bingads.v13.bulk import BulkFileReader from bingads.v13.bulk.exceptions import EntityReadException try: with BulkFileReader('/tmp/campaigns.csv') as reader: for entity in reader: process_entity(entity) except EntityReadException as e: print(f"Failed to read entity: {e.message}") print(f"Row values: {e.row_values}") if e.inner_exception: print(f"Cause: {e.inner_exception}") ``` -------------------------------- ### Configure BulkServiceManager for Production Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Instantiate BulkServiceManager for production use with custom polling interval and working directory. ```python from bingads.v13.bulk import BulkServiceManager # Production environment manager = BulkServiceManager( authorization_data=authorization_data, poll_interval_in_milliseconds=5000, environment='production', working_directory='/var/tmp/bingads' ) ``` -------------------------------- ### Select Bing Ads Environment Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/README.md Instantiate BulkServiceManager for either the production or sandbox environment. Always test in the sandbox environment before deploying to production. ```python # Production manager = BulkServiceManager(authorization_data, environment='production') # Sandbox manager = BulkServiceManager(authorization_data, environment='sandbox') ``` -------------------------------- ### BulkFileReader Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Initializes the BulkFileReader with file path, type, result type, and encoding. Supports context manager protocol. ```python def __init__(self, file_path, file_type='Csv', result_file_type=ResultFileType.full_download, encoding='utf-8-sig'): ``` -------------------------------- ### Create Bulk Service Manager Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/README.md Initialize the BulkServiceManager with your authorization data and environment. This manager is used for bulk operations. ```python from bingads.v13.bulk import BulkServiceManager manager = BulkServiceManager( authorization_data=authorization_data, environment='production' ) ``` -------------------------------- ### Configure Sandbox OAuth Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Set up OAuth for the sandbox environment using OAuthWebAuthCodeGrant. This is useful for testing and requires sandbox-specific credentials and IDs. ```python from bingads.authorization import AuthorizationData, OAuthWebAuthCodeGrant auth = OAuthWebAuthCodeGrant( client_id='your_sandbox_client_id', client_secret='your_sandbox_client_secret', redirection_uri='https://your-domain.com/callback', env='sandbox', oauth_scope='msads.manage' ) sandbox_auth_data = AuthorizationData( account_id=1234567, # Sandbox account ID customer_id=7654321, # Sandbox customer ID developer_token='your_sandbox_developer_token', authentication=auth ) ``` -------------------------------- ### BulkFileWriter Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Initializes a new instance of the BulkFileWriter class. It supports specifying the file path and encoding. ```APIDOC ## BulkFileWriter Constructor ### Description Initializes a new instance of the BulkFileWriter class, allowing for the creation of a bulk file writer with a specified file path and optional encoding. ### Parameters #### Path Parameters - **file_path** (str) - Required - The path of the bulk file to write. - **encoding** (str) - Optional - The encoding to use for the file. Defaults to 'utf-8-sig'. ``` -------------------------------- ### Configure Production OAuth for Desktop/Mobile Application Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Set up OAuth for desktop or mobile applications in the production environment using OAuthDesktopMobileAuthCodeGrant. Requires client ID and scope. ```python from bingads.authorization import ( AuthorizationData, OAuthDesktopMobileAuthCodeGrant ) auth = OAuthDesktopMobileAuthCodeGrant( client_id='your_desktop_app_client_id', env='production', oauth_scope='msads.manage' ) authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` -------------------------------- ### EntityUploadParameters Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-parameters.md Describes the parameters for uploading a collection of bulk entities. This includes specifying entities, result file details, and response modes. ```python def __init__(self, entities, result_file_directory=None, result_file_name=None, overwrite_result_file=False, response_mode='ErrorsAndResults', timeout_in_milliseconds=None): ``` -------------------------------- ### OAuthDesktopMobileImplicitGrant Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Initializes the OAuthDesktopMobileImplicitGrant object. Requires a client ID and optionally accepts OAuth tokens, environment, scope, tenant, and MSA production endpoint usage. ```python def __init__(self, client_id, oauth_tokens=None, env='production', oauth_scope='msads.manage', tenant='common', use_msa_prod=True): ``` -------------------------------- ### Configure BulkServiceManager for Sandbox Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Instantiate BulkServiceManager for sandbox testing with a longer polling interval. ```python # Sandbox environment for testing sandbox_manager = BulkServiceManager( authorization_data=authorization_data, environment='sandbox', poll_interval_in_milliseconds=10000 # Longer polling interval for sandbox ) ``` -------------------------------- ### Configure AuthorizationData for Bing Ads SDK Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Use this snippet to set up the necessary authorization data for SDK operations. Ensure you have obtained OAuth tokens and possess valid account and customer identifiers. ```python from bingads.authorization import ( AuthorizationData, OAuthWebAuthCodeGrant ) # Create OAuth authentication auth = OAuthWebAuthCodeGrant( client_id='your_client_id', client_secret='your_client_secret', redirection_uri='https://your-domain.com/callback' ) # Get OAuth tokens (user must grant permission) tokens = auth.request_oauth_tokens_by_response_uri(response_uri) # Create authorization data authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='ABCDEFGHIJKLMNOPabcdefghijklmnop', authentication=auth ) ``` -------------------------------- ### Initialize OAuthTokens Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Instantiate OAuthTokens with access token, expiration, and refresh token values. This is useful for managing authentication credentials. ```python from bingads.authorization import OAuthTokens tokens = OAuthTokens( access_token='access_token_value', access_token_expires_in_seconds=3600, refresh_token='refresh_token_value' ) if tokens.access_token_expired: print("Token has expired, refresh needed") ``` -------------------------------- ### AuthorizationData Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Initializes AuthorizationData with credentials and account identifiers. ```APIDOC ## AuthorizationData Constructor ### Description Initializes AuthorizationData with credentials and account identifiers required for Bing Ads API access. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Constructor Signature ```python def __init__(self, account_id=None, customer_id=None, developer_token=None, authentication=None): ``` ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | account_id | int | No | None | The identifier of the account that owns the entities in the request | | customer_id | int | No | None | The identifier of the customer that owns the account | | developer_token | str | No | None | The Bing Ads developer access token | | authentication | Authentication | No | None | An object representing the authentication method | ### Properties - **account_id** (int): The identifier of the account that owns the entities in the request - **customer_id** (int): The identifier of the customer that owns the account - **developer_token** (str): The Bing Ads developer access token - **authentication** (Authentication): An object representing the authentication method All properties support both getter and setter access. ### Example ```python from bingads.authorization import AuthorizationData, OAuthDesktopMobileAuthCodeGrant auth = OAuthDesktopMobileAuthCodeGrant(client_id='your_client_id') authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` ``` -------------------------------- ### ServiceClient Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/service-client.md Initializes the ServiceClient to manage HTTP communication with Bing Ads REST services. It requires service details, authentication credentials, and optional environment or location settings. ```APIDOC ## ServiceClient Constructor ### Description Initializes the ServiceClient to manage HTTP communication with Bing Ads REST services. It requires service details, authentication credentials, and optional environment or location settings. ### Signature ```python def __init__(self, service_name, version, authorization_data, environment='production', location=None, **suds_options): ``` ### Parameters #### Path Parameters * **service_name** (str) - Required - Name of the service (e.g., 'Bulk', 'CampaignManagement') * **version** (int) - Required - API version (typically 13) * **authorization_data** (AuthorizationData) - Required - Authorization credentials * **environment** (str) - Optional - Environment: 'production' or 'sandbox' (Default: 'production') * **location** (str) - Optional - Specific API location/endpoint (Default: None) * **suds_options** (dict) - Optional - Additional SUDS client options ``` -------------------------------- ### BulkFileReader Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Initializes a BulkFileReader to read entities from a specified bulk file. Supports different file types and encodings. ```APIDOC ## BulkFileReader Constructor ### Description Initializes a BulkFileReader to read entities from a specified bulk file. Supports different file types and encodings. ### Parameters #### Path Parameters - **file_path** (str) - Required - The path of the bulk file to read #### Query Parameters - **file_type** (str) - Optional - Default: 'Csv' - The bulk file type (typically 'Csv') - **result_file_type** (ResultFileType) - Optional - Default: ResultFileType.full_download - The result file type (full_download, partial_download, or upload) - **encoding** (str) - Optional - Default: 'utf-8-sig' - The encoding of the bulk file ``` -------------------------------- ### Download Campaigns and Entities Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/README.md Use DownloadParameters to specify what data to download, such as campaigns, ad groups, and ads. The download is saved to a specified file path. ```python from bingads.v13.bulk import DownloadParameters download_params = DownloadParameters( result_file_directory='/tmp', result_file_name='campaigns.csv', data_scope=['EntityData'], download_entities=['Campaign', 'AdGroup', 'TextAd'], timeout_in_milliseconds=600000 ) file_path = manager.download_file(download_params) print(f"Downloaded to: {file_path}") ``` -------------------------------- ### Initialize AuthorizationData with OAuth Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Instantiate AuthorizationData with account, customer, and developer token details, along with an OAuthDesktopMobileAuthCodeGrant authentication object. This is useful for setting up credentials for API requests. ```python from bingads.authorization import AuthorizationData, OAuthDesktopMobileAuthCodeGrant auth = OAuthDesktopMobileAuthCodeGrant(client_id='your_client_id') authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` -------------------------------- ### Initialize GoogleOAuthWebAuthCodeGrant Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Instantiate the GoogleOAuthWebAuthCodeGrant for web applications. Requires client ID, client secret, and redirect URL. ```python from bingads.authorization import GoogleOAuthWebAuthCodeGrant auth = GoogleOAuthWebAuthCodeGrant( client_id='your_google_client_id', client_secret='your_google_client_secret', redirect_url='https://your-domain.com/callback' ) endpoint = auth.get_authorization_endpoint() ``` -------------------------------- ### Configure Production OAuth for Web Application Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/configuration.md Set up OAuth for a web application in the production environment using OAuthWebAuthCodeGrant. Requires client ID, secret, redirection URI, and scope. ```python from bingads.authorization import ( AuthorizationData, OAuthWebAuthCodeGrant ) auth = OAuthWebAuthCodeGrant( client_id='your_web_app_client_id', client_secret='your_web_app_client_secret', redirection_uri='https://your-domain.com/callback', env='production', oauth_scope='msads.manage' ) authorization_data = AuthorizationData( account_id=1234567, customer_id=7654321, developer_token='your_developer_token', authentication=auth ) ``` -------------------------------- ### Incremental Downloads Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/README.md Download only the changes made since the last synchronization. Specify the `last_sync_time_in_utc` and the entities you wish to download. ```python from datetime import datetime, timedelta last_sync = datetime.utcnow() - timedelta(days=1) download_params = DownloadParameters( last_sync_time_in_utc=last_sync, download_entities=['Campaign', 'AdGroup'], timeout_in_milliseconds=600000 ) file_path = manager.download_file(download_params) ``` -------------------------------- ### Submit and Download Bulk Data Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/bulk-file-operations.md Use BulkDownloadOperation to submit a download request, check its status, and download the resulting file. Specify data scope, entities to download, and a timeout for the operation. ```python from bingads.v13.bulk import BulkServiceManager, DownloadParameters manager = BulkServiceManager(authorization_data) # Submit download download_params = DownloadParameters( data_scope=['EntityData'], download_entities=['Campaign'], timeout_in_milliseconds=600000 ) operation = manager.submit_download(download_params._submit_download_parameter) # Check status while not operation.is_completed(): status = operation.get_status() print(f"Status: {status.status}") import time time.sleep(5) # Download when ready result_file = operation.download_result_file( result_file_directory='/tmp', result_file_name='campaigns.csv' ) ``` -------------------------------- ### OAuthTokens Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Initializes a new instance of the OAuthTokens class with provided token details. ```APIDOC ## OAuthTokens Constructor ### Description Initializes a new instance of the OAuthTokens class. ### Method Signature ```python def __init__(self, access_token=None, access_token_expires_in_seconds=None, refresh_token=None, response_json=None): ``` ### Parameters #### Parameters - **access_token** (str) - Optional - None - OAuth access token for authorization - **access_token_expires_in_seconds** (int) - Optional - None - The access token expiration time in seconds - **refresh_token** (str) - Optional - None - OAuth refresh token that can be used to refresh an access token - **response_json** (dict) - Optional - None - The full JSON response from the OAuth service ``` -------------------------------- ### OAuthDesktopMobileAuthCodeGrant Constructor Source: https://github.com/bingads/bingads-python-sdk/blob/main/_autodocs/api-reference/authorization.md Initializes the OAuthDesktopMobileAuthCodeGrant object. Requires a client ID and allows configuration of tokens, environment, scope, tenant, and MSA endpoint usage. ```python def __init__(self, client_id, oauth_tokens=None, env='production', oauth_scope='msads.manage', tenant='common', use_msa_prod=True): ```