### Getting Started Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/GENERATION_SUMMARY.txt Begin your integration with the BytePlus Python SDK v2 by following the README.md for an overview and configuration.md for setup instructions. ```APIDOC ## Getting Started 1. **Overview**: Consult `README.md` for a general understanding of the SDK. 2. **Setup**: Refer to `configuration.md` for detailed setup and configuration options. 3. **Navigation**: Use `INDEX.md` to navigate through tasks and services. ``` -------------------------------- ### Install SDK via Setuptools Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/README.md Install the SDK using setup.py. Use --user for user-specific installation or sudo for system-wide installation. ```sh python setup.py install --user ``` -------------------------------- ### Install SDK via Pip Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/README.md Install the byteplus-python-sdk-v2 package using pip. ```sh pip install byteplus-python-sdk-v2 ``` -------------------------------- ### Initialize StaticCredentialProvider Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md Example of creating a StaticCredentialProvider and retrieving credential values. Ensure the provider is correctly instantiated with AK and SK. ```python from byteplussdkcore.auth.providers.static_provider import StaticCredentialProvider provider = StaticCredentialProvider(ak="test-ak", sk="test-sk") cred_value = provider.get_credentials() print(cred_value.ak) ``` -------------------------------- ### GET Request with Query Parameters Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-universal-api.md Illustrates how to make a GET request using the Universal API. For GET requests, the 'body' parameter is used to pass query parameters. ```python import byteplussdkcore api = byteplussdkcore.UniversalApi() # For GET requests, use body as query parameters info = byteplussdkcore.UniversalInfo( method='get', service='vpc', version='2020-04-01', action='DescribeVpcs' ) body = { 'MaxResults': 100, 'NextToken': 'token123' } response = api.do_call(info, body) print(response) ``` -------------------------------- ### Complete SDK Configuration Example Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/configuration.md This snippet shows how to set up global configuration for the BytePlus Python SDK, including credentials, endpoint, transport, retry, and logging settings. Use this for setting up default behavior across all SDK operations. ```python import byteplussdkcore from byteplussdkcore.auth.providers.sts_provider import StsCredentialProvider # Create configuration config = byteplussdkcore.Configuration() # Credentials (either static or provider) config.ak = "your-ak" config.sk = "your-sk" # OR use provider: # config.credential_provider = StsCredentialProvider(...) # Endpoint config.region = "ap-southeast-1" config.scheme = "https" # Transport config.connect_timeout = 30.0 config.read_timeout = 30.0 config.verify_ssl = True config.ssl_ca_cert = "/path/to/ca.pem" # Retry config.auto_retry = True config.num_max_retries = 3 config.min_retry_delay_ms = 100 config.max_retry_delay_ms = 1000 config.retry_error_codes = ['502', '503', '504'] # Logging config.debug = True config.logger_file = "/var/log/byteplus-sdk.log" config.logger_format = '%(asctime)s [%(levelname)s] %(message)s' # Validation config.client_side_validation = True # Set as default byteplussdkcore.Configuration.set_default(config) ``` -------------------------------- ### Credential Provider Setup with STS Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/README.md Demonstrates configuring the SDK to use STS (Security Token Service) for obtaining temporary credentials. This requires providing AK, SK, role name, and account ID. ```python from byteplussdkcore.auth.providers.sts_provider import StsCredentialProvider config = byteplussdkcore.Configuration() config.credential_provider = StsCredentialProvider( ak="your-ak", sk="your-sk", role_name="your-role", account_id="123456789" ) byteplussdkcore.Configuration.set_default(config) ``` -------------------------------- ### Network Interface Operations Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/FILE_MANIFEST.txt Provides examples for managing network interfaces, which are used to connect instances to a VPC. ```python from byteplus.vpc.api import VPCApi # Example of creating a network interface # vpc_api = VPCApi(api_client) # subnet_id = "subnet-xxxxxxxxxxxxxxxxx" # response = vpc_api.create_network_interface(subnet_id=subnet_id) # print(response) ``` -------------------------------- ### Query Parameter Encoding Example Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/FILE_MANIFEST.txt Demonstrates how query parameters are encoded for API requests. This is relevant for constructing requests with complex query strings. ```python # Example of query parameter encoding (conceptual) # query_params = { # "key1": "value1", # "key2": ["a", "b"] # } # encoded_query = urlencode(query_params) # Assuming urlencode from urllib.parse # print(encoded_query) # Expected output: key1=value1&key2=a&key2=b ``` -------------------------------- ### Python Response Type Example Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md Shows the standard format for response classes. Includes essential fields like next_token, request_id, and _metadata for tracking request details. ```python class DescribeVpcsResponse: """Response for DescribeVpcs action""" vpcs: list[Vpc] next_token: str request_id: str _metadata: ResponseMetadata # Response metadata ``` -------------------------------- ### Per-Request Configuration Override Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/configuration.md This example demonstrates how to override global SDK configurations for a specific API call using RuntimeOption. This is useful when a single request requires different settings, such as authentication or retry behavior, than the default configuration. ```python import byteplussdkcore import byteplussdkvpc from byteplussdkcore.interceptor import RuntimeOption # Global config config = byteplussdkcore.Configuration() config.ak = "default-ak" config.sk = "default-sk" byteplussdkcore.Configuration.set_default(config) # Per-request override runtime_opt = RuntimeOption( ak="override-ak", sk="override-sk", region="us-east-1", num_max_retries=5 ) request = byteplussdkvpc.CreateVpcRequest( cidr_block="10.0.0.0/16", _configuration=runtime_opt ) api = byteplussdkvpc.VPCApi() response = api.create_vpc(request) ``` -------------------------------- ### GET Request Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-universal-api.md Shows how to make a GET request, where the request body is used to pass query parameters. ```APIDOC ## GET Request ### Description This example demonstrates how to make a GET request. For GET requests, the parameters typically sent in the request body are instead passed as query parameters in the URL. ### Method `api.do_call(info, body)` ### Parameters - **info**: `UniversalInfo` object with `method='get'` specified. - **body**: Dictionary containing the query parameters for the GET request. ### Request Example ```python import byteplussdkcore api = byteplussdkcore.UniversalApi() # For GET requests, use body as query parameters info = byteplussdkcore.UniversalInfo( method='get', service='vpc', version='2020-04-01', action='DescribeVpcs' ) body = {{ 'MaxResults': 100, 'NextToken': 'token123' }} response = api.do_call(info, body) print(response) ``` ``` -------------------------------- ### Python Request Type Example Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md Illustrates the structure of a typical request class in the SDK. Fields are optional and often correspond to API parameters. Includes an optional _configuration for runtime overrides. ```python class DescribeVpcsRequest: """Request for DescribeVpcs action""" max_results: int | None next_token: str | None vpc_ids: list[str] | None filters: list[Filter] | None _configuration: RuntimeOption | None # Per-request config ``` -------------------------------- ### Using Enum Types in Requests Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md Provides an example of how to instantiate a request object, noting that enum fields like status are typically set by the server, not the client. ```python request = CreateVpcRequest( cidr_block="10.0.0.0/16", ) # status typically set by server, not client ``` -------------------------------- ### Form Data Flattening Example Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/FILE_MANIFEST.txt Illustrates how form data can be flattened for submission in API requests. This is useful for sending structured data in a flat format. ```python from byteplus.core.flatten import Flatten # Example of flattening form data # flatten = Flatten() # form_data = { # "user": { # "name": "John Doe", # "address": { # "street": "123 Main St", # "city": "Anytown" # } # } # } # flattened_form = flatten.flat(form_data, separator='_', root_ignore=True) # print(flattened_form) # Expected output: {'user_name': 'John Doe', 'user_address_street': '123 Main St', 'user_address_city': 'Anytown'} ``` -------------------------------- ### Python Model Type Examples Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md Demonstrates the structure of nested model classes used for complex parameters and responses. These classes support serialization and comparison methods. ```python class Vpc: vpc_id: str vpc_name: str cidr_block: str status: str created_at: str updated_at: str tags: dict[str, str] ``` ```python class Filter: name: str values: list[str] ``` ```python class TagSpecification: resource_type: str tags: dict[str, str] ``` -------------------------------- ### Flatten Nested Dictionary Example Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-flatten.md Demonstrates how to use the Flatten class to convert a nested dictionary with lists into a flat dictionary. The output keys are dot-separated by default, and list items are indexed starting from 1. ```python from byteplussdkcore.flatten import Flatten nested = { 'user': { 'name': 'Alice', 'email': 'alice@example.com' }, 'tags': ['python', 'sdk', 'api'] } flattened = Flatten(nested).flat() # Output: # { # 'user.name': 'Alice', # 'user.email': 'alice@example.com', # 'tags.1': 'python', # 'tags.2': 'sdk', # 'tags.3': 'api' # } ``` -------------------------------- ### Basic SDK Usage Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/README.md Demonstrates configuring credentials, creating an API client, making an API call, and accessing response metadata. Ensure necessary SDK modules are imported. ```python import byteplussdkcore import byteplussdkvpc # Configure credentials config = byteplussdkcore.Configuration() config.ak = "your-access-key" config.sk = "your-secret-key" config.region = "ap-southeast-1" byteplussdkcore.Configuration.set_default(config) # Create API client api = byteplussdkvpc.VPCApi() # Make API call request = byteplussdkvpc.DescribeVpcsRequest() response = api.describe_vpcs(request) # Access response for vpc in response.vpcs: print(f"VPC: {vpc.vpc_id} - {vpc.cidr_block}") # Get request metadata from byteplussdkcore.metadata import get_response_metadata metadata = get_response_metadata(response) print(f"Request ID: {metadata.request_id}") ``` -------------------------------- ### Basic Configuration with AK/SK Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-configuration.md Configure the SDK with your Access Key (AK), Secret Key (SK), and region. This is the most common way to authenticate and set up the SDK for basic usage. ```python import byteplussdkcore import byteplussdkvpc configuration = byteplussdkcore.Configuration() configuration.ak = "your-access-key" configuration.sk = "your-secret-key" configuration.region = "ap-southeast-1" byteplussdkcore.Configuration.set_default(configuration) api_client = byteplussdkvpc.VPCApi() response = api_client.describe_vpcs(byteplussdkvpc.DescribeVpcsRequest()) ``` -------------------------------- ### Create Configuration Instance Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-configuration.md Create a new Configuration instance. If no default has been set, this returns a default instance. Otherwise, it returns a copy of the currently set default configuration. ```python Configuration() ``` -------------------------------- ### ApiClient.user_agent Property Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-api-client.md Get or set the User-Agent header value for all requests made by the ApiClient. ```APIDOC ## ApiClient.user_agent Property ### Description Get or set the User-Agent header value for all requests. ### Method GET/SET ### Endpoint N/A (Property) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import byteplussdkcore api_client = byteplussdkcore.ApiClient() # Get User-Agent print(api_client.user_agent) # Set User-Agent api_client.user_agent = 'my-custom-agent/1.0' print(api_client.user_agent) ``` ### Response #### Success Response (200) - **user_agent** (str) - The User-Agent string. ``` -------------------------------- ### Create a VPC Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/service-vpc.md Use this to create a new VPC with specified CIDR block, name, description, DNS servers, and tags. Ensure the CIDR block is valid. ```python request = byteplussdkvpc.CreateVpcRequest( cidr_block="10.0.0.0/16", vpc_name="production-vpc", description="Main production network", dns_servers=["10.0.0.2", "10.0.0.3"], tags={"Environment": "prod", "Team": "platform"} ) response = api.create_vpc(request) vpc = response.vpc print(f"VPC {vpc.vpc_id} created with CIDR {vpc.cidr_block}") ``` -------------------------------- ### Type Validation Examples Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md The SDK validates request types before sending. Invalid types will raise `ValueError` or `TypeError`. ```python # Valid request = CreateVpcRequest(cidr_block="10.0.0.0/16", max_results=100) # Invalid - raises ValueError/TypeError before sending request request = CreateVpcRequest(max_results="not-an-int") # TypeError ``` -------------------------------- ### Create VPC Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/service-vpc.md Configure credentials and create a VPC client to create a new VPC with a specified CIDR block and name. ```python import byteplussdkcore import byteplussdkvpc # Configure credentials config = byteplussdkcore.Configuration() config.ak = "your-ak" config.sk = "your-sk" config.region = "ap-southeast-1" byteplussdkcore.Configuration.set_default(config) # Create VPC API client api = byteplussdkvpc.VPCApi() # Create a VPC response = api.create_vpc( byteplussdkvpc.CreateVpcRequest( cidr_block="10.0.0.0/16", vpc_name="my-vpc" ) ) print(f"Created VPC: {response.vpc.vpc_id}") ``` -------------------------------- ### Configure HTTP Proxy Settings Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/README.md Set up HTTP and HTTPS proxy servers for SDK requests. ```python config.https_proxy = "http://proxy.company.com:8080" config.http_proxy = "http://proxy.company.com:8080" ``` -------------------------------- ### Configuring List Indexing Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-flatten.md Control whether list elements are indexed starting from 0 or 1. The default is 1-based indexing. ```python from byteplussdkcore.flatten import Flatten data = { 'servers': [ 'server1.example.com', 'server2.example.com', 'server3.example.com' ] } # Default: 1-based indexing lattened = Flatten(data).flat() # Output: # { # 'servers.1': 'server1.example.com', # 'servers.2': 'server2.example.com', # 'servers.3': 'server3.example.com' # } # 0-based indexing lattened = Flatten(data, start_index=0).flat() # Output: # { # 'servers.0': 'server1.example.com', # 'servers.1': 'server2.example.com', # 'servers.2': 'server3.example.com' # } ``` -------------------------------- ### InterceptorContext Class Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-interceptor.md Holds request and response objects that flow through the interceptor chain. It provides methods to get and set the request and response. ```APIDOC ## Class: InterceptorContext **Module:** `byteplussdkcore.interceptor.interceptors.context` Holds request and response objects that flow through the interceptor chain. ### Constructor ```python InterceptorContext(request=None, response=None) ``` | Parameter | Type | Description | |-----------|------|-------------| | `request` | `Request` | Request object | | `response` | `Response` | Response object | ### Methods #### get_request() ```python def get_request(self) -> Request ``` Get the current request object. #### set_request(request) ```python def set_request(self, request: Request) -> None ``` Set/update the request object. #### get_response() ```python def get_response(self) -> Response ``` Get the current response object (available after request execution). #### set_response(response) ```python def set_response(self, response: Response) -> None ``` Set/update the response object. ``` -------------------------------- ### List All VPCs with Pagination Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/service-vpc.md Demonstrates how to retrieve all VPCs, handling pagination to ensure all resources are fetched. ```APIDOC ## List All VPCs with Pagination This function retrieves all VPCs by iteratively calling the `describe_vpcs` method, handling pagination using `next_token`. ```python def list_all_vpcs(api): all_vpcs = [] next_token = None while True: response = api.describe_vpcs( byteplussdkvpc.DescribeVpcsRequest( max_results=100, next_token=next_token ) ) all_vpcs.extend(response.vpcs) if not response.next_token: break next_token = response.next_token return all_vpcs ``` ``` -------------------------------- ### Configure SDK Settings Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/README.md Set up the SDK configuration, including client-side validation, schema, debug mode, and logger file. This configuration can be set as the default for the SDK. ```python configuration = byteplussdkcore.Configuration() configuration.client_side_validation = True configuration.schema = "http" configuration.debug = False configuration.logger_file = "sdk.log" byteplussdkcore.Configuration.set_default(configuration) ``` -------------------------------- ### ApiException __str__ Output Example Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/errors.md The string representation of an ApiException includes status, reason, headers, and body for detailed error analysis. ```text (400) Reason: Bad Request HTTP response headers: {'Content-Type': 'application/json', 'X-Tt-Logid': 'req-123'} HTTP response body: {"Code": "InvalidParameter", "Message": "CidrBlock is required"} ``` -------------------------------- ### Configure Proxy Settings Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-configuration.md Set up HTTP and HTTPS proxy servers for SDK requests. This is necessary when operating within a network that requires a proxy to access external services. ```python import byteplussdkcore config = byteplussdkcore.Configuration() config.https_proxy = "http://proxy.company.com:8080" config.http_proxy = "http://proxy.company.com:8080" byteplussdkcore.Configuration.set_default(config) ``` -------------------------------- ### STS SAML Credential Provider Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/configuration.md Use StsSamlCredentialProvider for SAML federation to get temporary credentials. Requires a base64-encoded SAML assertion and role name. ```python from byteplussdkcore.auth.providers.sts_saml_provider import StsSamlCredentialProvider provider = StsSamlCredentialProvider( saml_assertion="base64-encoded-saml", role_name="your-role", ) config.credential_provider = provider ``` -------------------------------- ### Initialize ApiClient Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-api-client.md Import and initialize the ApiClient. Optional custom configuration and default headers can be provided during initialization. ```python import byteplussdkcore api_client = byteplussdkcore.ApiClient() ``` -------------------------------- ### Configuration Constructor Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-configuration.md Creates a new Configuration instance. If no default has been set, returns a default instance. Otherwise, returns a copy of the default. ```APIDOC ## Constructor Configuration() ### Description Creates a new Configuration instance. If no default has been set, returns a default instance. Otherwise, returns a copy of the default. ### Method ```python Configuration() ``` ### Parameters This constructor does not accept any parameters. ### Request Example ```python import byteplussdkcore configuration = byteplussdkcore.Configuration() ``` ### Response Returns a Configuration instance. ``` -------------------------------- ### Initialize UniversalApi Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-universal-api.md Instantiate the UniversalApi client. An optional custom ApiClient can be provided; otherwise, a default one is created. ```python api = byteplussdkcore.UniversalApi() ``` -------------------------------- ### Asynchronous VPC Creation Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/service-vpc.md Illustrates how to create a VPC asynchronously, allowing other operations to proceed while the VPC is being created. ```APIDOC ## Asynchronous VPC Creation This example shows how to initiate VPC creation asynchronously using the `create_vpc` method with `async_req=True`. The result can be retrieved later using the `get()` method on the returned thread object. ```python # Create VPC asynchronously thread = api.create_vpc( byteplussdkvpc.CreateVpcRequest(cidr_block="10.0.0.0/16"), async_req=True ) # Do other work... # Get result response = thread.get() ``` ``` -------------------------------- ### Import Configuration Class Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-configuration.md Import the Configuration class from the byteplussdkcore module. This is the initial step to use the configuration. ```python import byteplussdkcore configuration = byteplussdkcore.Configuration() ``` -------------------------------- ### Safely Get Request ID Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-metadata.md Provides a utility function to safely extract a request ID from an API response, handling cases where metadata might be missing or incomplete. It returns 'unknown' as a fallback. ```python from byteplussdkcore.metadata import get_response_metadata def safe_get_request_id(response): """Safely extract request ID from response, with fallback""" metadata = get_response_metadata(response) if metadata and metadata.request_id: return metadata.request_id return "unknown" # Works with both typed models and dicts api_response = {'ResponseMetadata': {...}} request_id = safe_get_request_id(api_response) print(f"Tracked as: {request_id}") ``` -------------------------------- ### Basic API Call with ApiClient Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-api-client.md Demonstrates a basic synchronous API call using the ApiClient. Ensure you have configured your credentials and region. ```python import byteplussdkcore from byteplussdkcore.rest import ApiException config = byteplussdkcore.Configuration() config.ak = "your-ak" config.sk = "your-sk" config.region = "ap-southeast-1" byteplussdkcore.Configuration.set_default(config) api_client = byteplussdkcore.ApiClient() try: response = api_client.call_api( resource_path='/DescribeVpcs/2020-04-01/vpc/post/json/', method='POST', body={}, response_type='DescribeVpcsResponse', auth_settings=['byteplusSign'] ) print(response) except ApiException as e: print(f"Error {e.status}: {e.reason}") ``` -------------------------------- ### Create ResponseMetadata Instance Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-metadata.md Instantiate ResponseMetadata with service, request ID, action, version, and region details. ```python metadata = ResponseMetadata( service='vpc', request_id='req-abc123', action='CreateVpc', version='2020-04-01', region='ap-southeast-1' ) ``` -------------------------------- ### do_call Method Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-universal-api.md Executes a synchronous or asynchronous API call to a specified BytePlus service endpoint. Handles request body conversion to query parameters for GET requests and manages content type. ```APIDOC ### Methods #### do_call(info, body, **kwargs) ```python def do_call(self, info: UniversalInfo, body: dict, **kwargs) -> object | tuple ``` Execute a synchronous or asynchronous API call. | Parameter | Type | Description | |-----------|------|-------------| | `info` | `UniversalInfo` | Call information object describing the API endpoint | | `body` | `dict` | Request body (required, must be a dict) | | `async_req` | `bool` (kwarg) | If True, execute asynchronously | | `_return_http_data_only` | `bool` (kwarg) | If True, return only response body; default is True | | `_preload_content` | `bool` (kwarg) | If True, fully read response body; default is True | | `_request_timeout` | `float` (kwarg) | Request timeout override in seconds | **Returns:** - If `async_req=True`: Request thread (call `.get()` to retrieve result) - If `_return_http_data_only=True`: Deserialized response object - Otherwise: Tuple of (data, status_code, headers) **Raises:** - `ValueError`: If `body` is None or not a dict - `TypeError`: If body is not a dict - `ApiException`: On HTTP errors **Request Path Construction:** ``` /{action}/{version}/{service}/{method}/ ``` For example: `/CreateVpc/2020-04-01/vpc/post/` **Content-Type Handling:** - If `info.content_type` is set, uses that as the request Content-Type - Always accepts `application/json` responses **Query Parameters:** - For GET requests, the `body` dict is converted to query parameters **Authentication:** Uses `byteplusSign` authentication **Example:** ```python import byteplussdkcore api = byteplussdkcore.UniversalApi() # Create VPC info = byteplussdkcore.UniversalInfo( method='post', service='vpc', version='2020-04-01', action='CreateVpc' ) body = {'CidrBlock': '192.168.0.0/16'} response = api.do_call(info, body) print(response) ``` ``` -------------------------------- ### STS AssumeRole with Python SDK Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/docs/1-Credentials.md Obtain temporary credentials by assuming an IAM role using the Python SDK. Use these role credentials to perform actual API calls. Ensure not to leak credentials in example code. ```python from __future__ import print_function import byteplussdkcore import byteplussdkvpc from byteplussdkcore.rest import ApiException from byteplussdkcore.auth.providers.sts_provider import StsCredentialProvider if __name__ == '__main__': # Do NOT leak credentials in example code. configuration = byteplussdkcore.Configuration() configuration.region = "ap-singapore-1" configuration.credential_provider = StsCredentialProvider( ak="Your ak", sk="Your sk", role_name="Your role name", account_id="Your account id", duration_seconds=3600, scheme="https", host="open.byteplusapi.com", region="ap-singapore-1", timeout=30, expired_buffer_seconds=60, policy='{"Statement":[{"Effect":"Allow","Action":["vpc:CreateVpc"],"Resource":["*"],"Condition":{"StringEquals":{"byteplus:RequestedRegion":["ap-singapore-1"]}}}]}' ) byteplussdkcore.Configuration.set_default(configuration) api_instance = byteplussdkvpc.VPCApi() create_vpc_request = byteplussdkvpc.CreateVpcRequest( cidr_block="192.168.0.0/16", dns_servers=["10.0.0.1", "10.1.1.2"], ) try: api_instance.create_vpc(create_vpc_request) except ApiException: pass ``` -------------------------------- ### Instantiate RuntimeOption Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-interceptor.md Create a RuntimeOption object to configure per-request settings like access key, secret key, and region. These settings override global configurations. ```python runtime_option = RuntimeOption(ak="test-ak", sk="test-sk", region="us-east-1") print(runtime_option.ak) # "test-ak" print(runtime_option.region) # "us-east-1" ``` -------------------------------- ### UniversalApi Constructor Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-universal-api.md Initializes the UniversalApi with an optional custom API client. If no client is provided, a default one is created. ```APIDOC ## Class: UniversalApi **Module:** `byteplussdkcore.universal` Generic API client for calling any BytePlus service endpoint. ### Constructor ```python UniversalApi(api_client=None) ``` Initialize UniversalApi with an optional custom API client. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `api_client` | `ApiClient` | `ApiClient()` | API client instance; if None, creates a default one | ``` -------------------------------- ### List All VPCs with Pagination Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/service-vpc.md Iteratively fetches all VPCs by handling pagination using `next_token`. Useful for retrieving a complete list when the total number of VPCs exceeds the maximum results per page. ```python def list_all_vpcs(api): all_vpcs = [] next_token = None while True: response = api.describe_vpcs( byteplussdkvpc.DescribeVpcsRequest( max_results=100, next_token=next_token ) ) all_vpcs.extend(response.vpcs) if not response.next_token: break next_token = response.next_token return all_vpcs ``` -------------------------------- ### Comprehensive Error Handling in Python Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/docs/7-ErrorHandling.md This example demonstrates how to catch and handle various error types, including network/timeout errors, client-side validation errors, SSL authentication errors, server-side business logic errors, and general exceptions. It shows how to extract specific error details like RequestId and Error Message from ApiException. ```python import json import socket import urllib3 import byteplussdkcore, byteplussdkecs from byteplussdkcore.rest import ApiException configuration = byteplussdkcore.Configuration() configuration.ak = "Your ak" configuration.sk = "Your sk" byteplussdkcore.Configuration.set_default(configuration) api_instance = byteplussdkecs.ECSApi() create_command_request = byteplussdkecs.CreateCommandRequest( command_content="ls -l", description="Your command description", name="Your command name", type="command", ) network_error_exceptions = ( urllib3.exceptions.NewConnectionError, urllib3.exceptions.ConnectTimeoutError, urllib3.exceptions.ReadTimeoutError, urllib3.exceptions.ProtocolError, socket.timeout, socket.gaierror, ) try: api_instance.create_command(create_command_request) except network_error_exceptions as e: print("1. Network/timeout error:{}".format(e)) except ValueError as e: print("2. Client error (parameter validation error):{}".format(e)) except ApiException as e: if e.status == 0: print("2. Client error (SSL authentication error):{}".format(e.reason)) else: print("3. Server error:") if e.body is not None: response_meta_data = json.loads(e.body).get("ResponseMetadata") print("RequestId:{}".format(response_meta_data.get("RequestId"))) print("Error Code: {}".format(response_meta_data.get("Error").get("Code"))) print("Error Message: {}".format(response_meta_data.get("Error").get("Message")))) except Exception as e: print("4. Other error:%s" % e) ``` -------------------------------- ### Use CLI Config Credential Provider Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/docs/1-Credentials.md Configure the SDK to use the CLI config provider, specifying a profile and config path. Ensure the config file exists and is correctly formatted. ```python import os import byteplussdkcore from byteplussdkcore.auth.providers.cli_config_provider import CLIConfigCredentialProvider configuration = byteplussdkcore.Configuration() configuration.region = "ap-southeast-1" configuration.credential_provider = CLIConfigCredentialProvider( profile_name="prod", config_path=os.path.expanduser("~/.byteplus/config.json"), ) byteplussdkcore.Configuration.set_default(configuration) ``` -------------------------------- ### With HTTP Headers Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-universal-api.md Demonstrates how to add custom HTTP headers to API requests. ```APIDOC ## With HTTP Headers ### Description This example shows how to set custom HTTP headers for all requests made by an `ApiClient` instance. This is useful for passing authentication tokens, custom identifiers, or other metadata required by the API. ### Method `api = byteplussdkcore.UniversalApi(api_client=api_client)` ### Parameters - **api_client**: An instance of `ApiClient` where default headers have been set using `set_default_header()`. ### Request Example ```python import byteplussdkcore api_client = byteplussdkcore.ApiClient() api_client.set_default_header('X-Custom-Header', 'custom-value') api = byteplussdkcore.UniversalApi(api_client=api_client) info = byteplussdkcore.UniversalInfo( method='post', service='vpc', version='2020-04-01', action='DescribeVpcs' ) response = api.do_call(info, {{}}) ``` ``` -------------------------------- ### SDK Architecture Overview Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/README.md Illustrates the layered architecture of the BytePlus Python SDK, showing the flow from application code to the underlying REST client. ```text Application Code ↓ Service-Specific API Classes (VPCApi, ECSApi, ...) ↓ Generic UniversalApi ↓ ApiClient (Core HTTP client) ↓ Interceptor Chain ├─ BuildRequestInterceptor ├─ RuntimeOptionsInterceptor ├─ ResolveEndpointInterceptor ├─ SignRequestInterceptor └─ DeserializedResponseInterceptor ↓ REST Client (urllib3) ``` -------------------------------- ### ApiClient Constructor Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-api-client.md Initializes an ApiClient instance with optional custom configuration and default headers. ```APIDOC ## ApiClient Constructor ### Description Initialize an ApiClient with optional custom configuration and default headers. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import byteplussdkcore # Initialize with default configuration api_client = byteplussdkcore.ApiClient() # Initialize with custom configuration and headers from byteplussdkcore.configuration import Configuration config = Configuration(debug=True) api_client_custom = byteplussdkcore.ApiClient(configuration=config, header_name='X-Custom-Header', header_value='custom-value', cookie='sessionid=abc') ``` ### Response None ``` -------------------------------- ### API Reference and Service Documentation Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/GENERATION_SUMMARY.txt Access detailed API references for core SDK methods and specific services like VPC. Use service-specific documentation as a template for other services. ```APIDOC ## API Reference - **Core SDK Methods**: Review `api-reference/core-*.md` for documentation on over 50 core SDK methods. - **Service Documentation**: Examine `service-vpc.md` for an example of service-specific API documentation. This can be used as a template for documenting other services. - **Type Information**: Consult `types.md` for details on data types used within the SDK. ``` -------------------------------- ### Request Tracing for Single Operation Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-metadata.md Demonstrates how to capture and log metadata, including the request ID, for a single API operation like creating a VPC. Includes error handling for API exceptions and attempts to extract metadata from error responses. ```python import byteplussdkcore import byteplussdkvpc from byteplussdkcore.metadata import get_response_metadata from byteplussdkcore.rest import ApiException config = byteplussdkcore.Configuration() config.ak = "your-ak" config.sk = "your-sk" byteplussdkcore.Configuration.set_default(config) api = byteplussdkvpc.VPCApi() def create_vpc_with_tracing(cidr_block): try: response = api.create_vpc( byteplussdkvpc.CreateVpcRequest(cidr_block=cidr_block) ) metadata = get_response_metadata(response) if metadata: print(f"Success! VPC created with request ID: {metadata.request_id}") print(f"Details:") print(f" - Service: {metadata.service}") print(f" - Action: {metadata.action}") print(f" - Region: {metadata.region}") print(f" - Version: {metadata.version}") return response except ApiException as e: print(f"Failed! Status: {e.status}") # For errors, metadata might be in response body if e.body: import json try: error_data = json.loads(e.body.decode('utf-8')) metadata = get_response_metadata(error_data) if metadata: print(f"Error request ID: {metadata.request_id}") except Exception: pass raise create_vpc_with_tracing('10.0.0.0/16') ``` -------------------------------- ### List Format for API Parameters Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md Demonstrates how to define a list of strings for API parameters. The SDK handles conversion to comma-separated values for query parameters or multi-value for form parameters. ```python # Default: Comma-separated values tags: list[str] = ["python", "sdk", "api"] # Query param: tags=python,sdk,api # Form param: tags=python&tags=sdk&tags=api (multi-value) ``` -------------------------------- ### Import Flatten Utility Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-flatten.md Import the Flatten class from the byteplussdkcore.flatten module. ```python from byteplussdkcore.flatten import Flatten ``` -------------------------------- ### create_vpc Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/service-vpc.md Creates a new Virtual Private Cloud (VPC) with the specified configuration. This includes defining the CIDR block, name, description, DNS servers, and tags. ```APIDOC ## create_vpc ### Description Create a new VPC. ### Method POST (Assumed based on creation operation) ### Endpoint /vpcs (Assumed based on typical REST patterns for VPC creation) ### Parameters #### Request Body - **cidr_block** (str) - Required - CIDR block (e.g., `10.0.0.0/16`) - **vpc_name** (str) - Optional - VPC name (max 128 chars) - **description** (str) - Optional - VPC description (max 256 chars) - **dns_servers** (list[str]) - Optional - Custom DNS servers - **tags** (dict[str, str]) - Optional - Resource tags ### Request Example ```python request = byteplussdkvpc.CreateVpcRequest( cidr_block="10.0.0.0/16", vpc_name="production-vpc", description="Main production network", dns_servers=["10.0.0.2", "10.0.0.3"], tags={"Environment": "prod", "Team": "platform"} ) response = api.create_vpc(request) vpc = response.vpc print(f"VPC {vpc.vpc_id} created with CIDR {vpc.cidr_block}") ``` ### Response #### Success Response (200) - **vpc** (Vpc) - The created VPC object. - **_metadata** (ResponseMetadata) - Metadata about the response. #### Response Example ```json { "vpc": { "vpc_id": "vpc-abcdef1234567890", "cidr_block": "10.0.0.0/16", "vpc_name": "production-vpc", "description": "Main production network", "dns_servers": ["10.0.0.2", "10.0.0.3"], "tags": {"Environment": "prod", "Team": "platform"}, "creation_time": "2023-10-27T10:00:00Z", "status": "Available" }, "_metadata": { "request_id": "abcdef1234567890", "action": "CreateVpc", "version": "1.0" } } ``` ### Errors - `ApiException` on error (e.g., 400 for invalid CIDR) ``` -------------------------------- ### Core Flatten Utility Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/FILE_MANIFEST.txt Documentation for the core flatten utility, including its `flat()` method, constructor parameters, and various usage scenarios. ```APIDOC ## Flatten Utility ### Description Provides a utility for flattening nested data structures. Supports customization of separators, list indexing, and root key ignoring. ### Methods #### `flat(data, separator='.', root_key_ignore=False, start_index=0)` Flattens a nested dictionary or list into a single-level dictionary. - **data** (dict or list) - The nested structure to flatten. - **separator** (str, optional) - The separator to use between keys. Defaults to '.'. - **root_key_ignore** (bool, optional) - If True, ignores the root key. Defaults to False. - **start_index** (int, optional) - The starting index for list elements. Defaults to 0. ### Usage Examples Includes 8+ usage examples covering query parameter encoding, form data flattening, and common pitfalls. ``` -------------------------------- ### Enable Debug Logging Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/README.md Activate debug logging for the SDK and specify a file path to store the log output. ```python config.debug = True config.logger_file = "/var/log/byteplus-sdk.log" ``` -------------------------------- ### Basic Error Handling with ApiException Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/errors.md Demonstrates how to catch and print details of an ApiException, including status, reason, body, and headers. Use this for general error reporting. ```python import byteplussdkcore import byteplussdkvpc from byteplussdkcore.rest import ApiException config = byteplussdkcore.Configuration() config.ak = "your-ak" config.sk = "your-sk" byteplussdkcore.Configuration.set_default(config) api = byteplussdkvpc.VPCApi() try: request = byteplussdkvpc.CreateVpcRequest(cidr_block="invalid-cidr") api.create_vpc(request) except ApiException as e: print(f"Status: {e.status}") print(f"Reason: {e.reason}") print(f"Body: {e.body}") print(f"Headers: {e.headers}") ``` -------------------------------- ### Configure Standard Endpoint Resolution with DualStack and Region Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/docs/2-Endpoint.md Set up the standard endpoint resolver, enable dual-stack support, and specify the region for the SDK's endpoint configuration. ```python import byteplussdkcore from byteplussdkcore.endpoint.providers.standard_provider import StandardEndpointResolver configuration = byteplussdkcore.Configuration() configuration.ak = "Your ak" configuration.sk = "Your sk" configuration.endpoint_provider = StandardEndpointResolver() # Configure standard resolution configuration.use_dual_stack = True # Configure dual-stack configuration.region = "ap-southeast-1" # Configure region byteplussdkcore.Configuration.set_default(configuration) ``` -------------------------------- ### Handling Date/Time Types in SDK Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/types.md Demonstrates how the SDK automatically converts ISO 8601 strings to Python datetime objects for requests and includes datetime fields in responses. ```python import datetime # ISO 8601 strings are automatically converted to datetime request = DescribeVpcsRequest() # Response includes datetime fields response = api.describe_vpcs(request) for vpc in response.vpcs: print(vpc.created_at) # type: datetime.datetime ``` -------------------------------- ### Request Class Constructor Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-interceptor.md Initializes a new Request object with configuration and request details. ```APIDOC ## Class: Request **Module:** `byteplussdkcore.interceptor.interceptors.request` Encapsulates a complete HTTP request with all metadata and configuration. ### Constructor ```python Request( configuration, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, _return_http_data_only=None, collection_formats=None, _preload_content=True, _request_timeout=None ) ``` | Parameter | Type | Description | |-----------|------|-------------| | `configuration` | `Configuration` | SDK configuration | | `resource_path` | `str` | API endpoint path | | `method` | `str` | HTTP method | | `path_params` | `dict` | Path parameters | | `query_params` | `list` | Query parameters | | `header_params` | `dict` | Request headers | | `body` | `dict` | Request body | | `post_params` | `list` | POST form parameters | | `files` | `dict` | Files for upload | | `response_type` | `str` | Expected response type | | `auth_settings` | `list` | Authentication mechanisms | | `_return_http_data_only` | `bool` | Return data-only flag | | `collection_formats` | `dict` | Collection format settings | | `_preload_content` | `bool` | Preload response flag | | `_request_timeout` | `float` | Request timeout | ``` -------------------------------- ### Regenerating or Updating Documentation Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/GENERATION_SUMMARY.txt Instructions on how to regenerate or update the SDK documentation from the source code. ```APIDOC ## Regeneration Process To regenerate or update documentation: 1. **Re-analyze**: Run analysis on the source code in `/workspace/home/byteplus-python-sdk-v2`. 2. **Update Files**: Update the `.md` files located in `/workspace/home/output/`. 3. **Maintain Structure**: Adhere to the existing structure and format. 4. **Consistency**: Ensure examples remain consistent. 5. **Validate**: Validate the generated documentation against the actual source code. ``` -------------------------------- ### Extending Documentation for New Services Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/GENERATION_SUMMARY.txt Guidelines for documenting additional services by following the pattern established by the VPC service documentation. ```APIDOC ## Extending Documentation To document additional services: 1. **Template**: Copy `api-reference/service-vpc.md`. 2. **Rename**: Replace 'VPC' with the target service name. 3. **Extract APIs**: Get API methods from the corresponding `service_api.py` file. 4. **Document Models**: Document request and response models. 5. **Examples**: Provide service-specific usage examples. 6. **Update Index**: Add the new service reference to `INDEX.md`. ``` -------------------------------- ### Create UniversalInfo Object Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/core-universal-api.md Instantiate a UniversalInfo object to describe a Universal API call. Specify the HTTP method, service name, API version, and action. ```python import byteplussdkcore info = byteplussdkcore.UniversalInfo( method='post', service='vpc', version='2020-04-01', action='CreateVpc' ) ``` -------------------------------- ### Create Network Interface Source: https://github.com/byteplus-sdk/byteplus-python-sdk-v2/blob/main/_autodocs/api-reference/service-vpc.md Creates a network interface (ENI) within your VPC. This allows for additional network connectivity for instances. ```python def create_network_interface(self, body: CreateNetworkInterfaceRequest, **kwargs) -> CreateNetworkInterfaceResponse: """Create a network interface (ENI).""" pass ```