mypy-boto3-ce: Type Annotations for AWS Cost Explorer

1.42.28 · active · verified Sat Apr 11

mypy-boto3-ce provides comprehensive type annotations for the AWS Boto3 Cost Explorer (CE) service, ensuring static type checking for your Python code. It is automatically generated by `mypy-boto3-builder` (currently version 8.12.0) and is updated frequently to align with `boto3` and `botocore` releases, enhancing code quality and developer experience by catching potential AWS-related errors before runtime.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize a Boto3 Cost Explorer client with type hints from `mypy-boto3-ce` and use it to retrieve cost and usage data. It uses the `TYPE_CHECKING` guard to ensure `mypy-boto3-ce` is only a development dependency.

from typing import TYPE_CHECKING
import boto3
import os

if TYPE_CHECKING:
    from mypy_boto3_ce.client import CostExplorerClient
    from mypy_boto3_ce.type_defs import GetCostAndUsageResponseTypeDef


# It's recommended to use explicit type hints for boto3.client for better IDE support
# and type checking, especially if not using the 'boto3-stubs' full package.
def get_cost_explorer_data(client: "CostExplorerClient") -> "GetCostAndUsageResponseTypeDef":
    # Example: Retrieve cost and usage data for the last 7 days
    response = client.get_cost_and_usage(
        TimePeriod={
            'Start': '2023-01-01',
            'End': '2023-01-08'
        },
        Granularity='DAILY',
        Metrics=['BlendedCost', 'UnblendedCost'],
        # Add other parameters as needed, e.g., Filter, GroupBy
    )
    return response


if __name__ == '__main__':
    # Ensure AWS credentials are configured (e.g., via environment variables or AWS CLI config)
    # For this example, we'll create a client. In a real app, you might pass an existing client.
    print("Initializing Boto3 Cost Explorer client...")
    ce_client: "CostExplorerClient" = boto3.client(
        "ce", 
        region_name=os.environ.get('AWS_REGION', 'us-east-1'),
        aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID', 'DUMMY_KEY'),
        aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY', 'DUMMY_SECRET')
    )
    
    try:
        # The `get_cost_explorer_data` function now benefits from type hints
        # for both the client object and the response structure.
        costs_data = get_cost_explorer_data(ce_client)
        print("Successfully retrieved Cost Explorer data (truncated for brevity):")
        # In a real scenario, you'd process costs_data. For this example, just print a key.
        if costs_data and 'ResultsByTime' in costs_data:
            print(f"First result time period: {costs_data['ResultsByTime'][0]['TimePeriod']}")
        else:
            print("No results or unexpected response structure.")
    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →