Skip to content

get_cost_and_usage async

get_cost_and_usage(
    time_period: DateInterval,
    granularity: Granularity,
    metrics: MetricNames,
    *,
    config_overrides: Optional[AsyncCostExplorerClientConfig] = None,
    filter: Optional[Expression] = None,
    group_by: Optional[GroupDefinitions] = None,
    billing_view_arn: Optional[BillingViewArn] = None,
    next_page_token: Optional[NextPageToken] = None,
) -> GetCostAndUsageResponse

Retrieves cost and usage metrics for your account. You can specify which cost and usage-related metric that you want the request to return. For example, you can specify BlendedCosts or UsageQuantity. You can also filter and group your data by various dimensions, such as SERVICE or AZ, in a specific time range. For a complete list of valid dimensions, see the GetDimensionValues operation. Management account in an organization in Organizations have access to all member accounts.

For information about filter limitations, see Quotas and restrictions in the Billing and Cost Management User Guide.

Parameters:

  • time_period (DateInterval) –

    Sets the start date and end date for retrieving Amazon Web Services costs. The start date is inclusive, but the end date is exclusive. For example, if start is 2017-01-01 and end is 2017-05-01, then the cost and usage data is retrieved from 2017-01-01 up to and including 2017-04-30 but not including 2017-05-01.

  • granularity (Granularity) –

    Sets the Amazon Web Services cost granularity to MONTHLY or DAILY, or HOURLY. If Granularity isn't set, the response object doesn't include the Granularity, either MONTHLY or DAILY, or HOURLY.

  • filter (Optional[Expression], default: None ) –

    Filters Amazon Web Services costs by different dimensions. For example, you can specify SERVICE and LINKED_ACCOUNT and get the costs that are associated with that account's usage of that service. You can nest Expression objects to define any combination of dimension filters. For more information, see Expression.

    Valid values for MatchOptions for Dimensions are EQUALS and CASE_SENSITIVE.

    Valid values for MatchOptions for CostCategories, Tags, and ProductAttributes are EQUALS, ABSENT, and CASE_SENSITIVE. Default values are EQUALS and CASE_SENSITIVE.

    You can filter by product attributes with or without grouping by them. If you filter or group by product attributes, the results include only the costs of supported services, and a SERVICE filter is optional. For more information, see ProductAttributeValues.

    If you include a SERVICE filter, it must apply to the whole request: combine it with other filters by using And, and include it in every branch of an Or. A SERVICE filter inside Not doesn't meet this requirement, and the request fails with a ValidationException.

  • metrics (MetricNames) –

    Which metrics are returned in the query. For more information about blended and unblended rates, see Why does the "blended" annotation appear on some line items in my bill?.

    Valid values are AmortizedCost, BlendedCost, NetAmortizedCost, NetUnblendedCost, NormalizedUsageAmount, UnblendedCost, and UsageQuantity.

    If you return the UsageQuantity metric, the service aggregates all usage numbers without taking into account the units. For example, if you aggregate usageQuantity across all of Amazon EC2, the results aren't meaningful because Amazon EC2 compute hours and data transfer are measured in different units (for example, hours and GB). To get more meaningful UsageQuantity metrics, filter by UsageType or UsageTypeGroups.

    Metrics is required for GetCostAndUsage requests.

  • group_by (Optional[GroupDefinitions], default: None ) –

    You can group Amazon Web Services costs using up to two different groups, either dimensions, tag keys, cost categories, product attributes, or any two group by types.

    Valid values for the DIMENSION type are AZ, INSTANCE_TYPE, LEGAL_ENTITY_NAME, INVOICING_ENTITY, LINKED_ACCOUNT, OPERATION, PLATFORM, PURCHASE_TYPE, SERVICE, TENANCY, RECORD_TYPE, and USAGE_TYPE.

    When you group by the TAG type and include a valid tag key, you get all tag values, including empty strings.

    To group by the PRODUCT_ATTRIBUTE type, set Key to a product attribute key, such as model. For the keys of each supported service, see ProductAttributeValues. The results include only the costs of supported services, and if you have no such costs, the response contains no groups.

    In the response, each group key has the format key$value, for example, model$Claude Sonnet 5. Costs that have no value for the key are in the group key$, for example, model$. Remove the key$ prefix before you use a value in a ProductAttributes filter. Keys are case-sensitive: if you group by a key that doesn't exist, such as Model, all of your costs of supported services are in the group Model$.

  • billing_view_arn (Optional[BillingViewArn], default: None ) –

    The Amazon Resource Name (ARN) that uniquely identifies a specific billing view. The ARN is used to specify which particular billing view you want to interact with or retrieve information from when making API calls related to Amazon Web Services Billing and Cost Management features. The BillingViewArn can be retrieved by calling the ListBillingViews API.

  • next_page_token (Optional[NextPageToken], default: None ) –

    The token to retrieve the next set of results. Amazon Web Services provides the token when the response from a previous call has more results than the maximum page size.

Raises:

Source code in docs_src/capo_cost_explorer/_services/async_cost_explorer.py
async def get_cost_and_usage(
    self,
    time_period: "capo_cost_explorer.types.date_interval.DateInterval",
    granularity: "capo_cost_explorer.types.granularity.Granularity",
    metrics: "capo_cost_explorer.types.metric_names.MetricNames",
    *,
    config_overrides: Optional[AsyncCostExplorerClientConfig] = None,
    filter: Optional["capo_cost_explorer.types.expression.Expression"] = None,
    group_by: Optional[
        "capo_cost_explorer.types.group_definitions.GroupDefinitions"
    ] = None,
    billing_view_arn: Optional[
        "capo_cost_explorer.types.billing_view_arn.BillingViewArn"
    ] = None,
    next_page_token: Optional[
        "capo_cost_explorer.types.next_page_token.NextPageToken"
    ] = None,
) -> "capo_cost_explorer.types.get_cost_and_usage_response.GetCostAndUsageResponse":
    """<p>Retrieves cost and usage metrics for your account. You can specify which cost and usage-related metric that you want the request to return. For example, you can specify <code>BlendedCosts</code> or <code>UsageQuantity</code>. You can also filter and group your data by various dimensions, such as <code>SERVICE</code> or <code>AZ</code>, in a specific time range. For a complete list of valid dimensions, see the <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_GetDimensionValues.html">GetDimensionValues</a> operation. Management account in an organization in Organizations have access to all member accounts.</p> <p>For information about filter limitations, see <a href="https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-limits.html">Quotas and restrictions</a> in the <i>Billing and Cost Management User Guide</i>.</p>

    Args:
        time_period: <p>Sets the start date and end date for retrieving Amazon Web Services costs. The start date is inclusive, but the end date is exclusive. For example, if <code>start</code> is <code>2017-01-01</code> and <code>end</code> is <code>2017-05-01</code>, then the cost and usage data is retrieved from <code>2017-01-01</code> up to and including <code>2017-04-30</code> but not including <code>2017-05-01</code>.</p>
        granularity: <p>Sets the Amazon Web Services cost granularity to <code>MONTHLY</code> or <code>DAILY</code>, or <code>HOURLY</code>. If <code>Granularity</code> isn't set, the response object doesn't include the <code>Granularity</code>, either <code>MONTHLY</code> or <code>DAILY</code>, or <code>HOURLY</code>. </p>
        filter: <p>Filters Amazon Web Services costs by different dimensions. For example, you can specify <code>SERVICE</code> and <code>LINKED_ACCOUNT</code> and get the costs that are associated with that account's usage of that service. You can nest <code>Expression</code> objects to define any combination of dimension filters. For more information, see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_Expression.html">Expression</a>. </p> <p>Valid values for <code>MatchOptions</code> for <code>Dimensions</code> are <code>EQUALS</code> and <code>CASE_SENSITIVE</code>.</p> <p>Valid values for <code>MatchOptions</code> for <code>CostCategories</code>, <code>Tags</code>, and <code>ProductAttributes</code> are <code>EQUALS</code>, <code>ABSENT</code>, and <code>CASE_SENSITIVE</code>. Default values are <code>EQUALS</code> and <code>CASE_SENSITIVE</code>.</p> <p>You can filter by product attributes with or without grouping by them. If you filter or group by product attributes, the results include only the costs of supported services, and a <code>SERVICE</code> filter is optional. For more information, see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_ProductAttributeValues.html">ProductAttributeValues</a>.</p> <p>If you include a <code>SERVICE</code> filter, it must apply to the whole request: combine it with other filters by using <code>And</code>, and include it in every branch of an <code>Or</code>. A <code>SERVICE</code> filter inside <code>Not</code> doesn't meet this requirement, and the request fails with a <code>ValidationException</code>.</p>
        metrics: <p>Which metrics are returned in the query. For more information about blended and unblended rates, see <a href="http://aws.amazon.com/premiumsupport/knowledge-center/blended-rates-intro/">Why does the "blended" annotation appear on some line items in my bill?</a>. </p> <p>Valid values are <code>AmortizedCost</code>, <code>BlendedCost</code>, <code>NetAmortizedCost</code>, <code>NetUnblendedCost</code>, <code>NormalizedUsageAmount</code>, <code>UnblendedCost</code>, and <code>UsageQuantity</code>. </p> <note> <p>If you return the <code>UsageQuantity</code> metric, the service aggregates all usage numbers without taking into account the units. For example, if you aggregate <code>usageQuantity</code> across all of Amazon EC2, the results aren't meaningful because Amazon EC2 compute hours and data transfer are measured in different units (for example, hours and GB). To get more meaningful <code>UsageQuantity</code> metrics, filter by <code>UsageType</code> or <code>UsageTypeGroups</code>. </p> </note> <p> <code>Metrics</code> is required for <code>GetCostAndUsage</code> requests.</p>
        group_by: <p>You can group Amazon Web Services costs using up to two different groups, either dimensions, tag keys, cost categories, product attributes, or any two group by types.</p> <p>Valid values for the <code>DIMENSION</code> type are <code>AZ</code>, <code>INSTANCE_TYPE</code>, <code>LEGAL_ENTITY_NAME</code>, <code>INVOICING_ENTITY</code>, <code>LINKED_ACCOUNT</code>, <code>OPERATION</code>, <code>PLATFORM</code>, <code>PURCHASE_TYPE</code>, <code>SERVICE</code>, <code>TENANCY</code>, <code>RECORD_TYPE</code>, and <code>USAGE_TYPE</code>.</p> <p>When you group by the <code>TAG</code> type and include a valid tag key, you get all tag values, including empty strings.</p> <p>To group by the <code>PRODUCT_ATTRIBUTE</code> type, set <code>Key</code> to a product attribute key, such as <code>model</code>. For the keys of each supported service, see <a href="https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_ProductAttributeValues.html">ProductAttributeValues</a>. The results include only the costs of supported services, and if you have no such costs, the response contains no groups.</p> <p>In the response, each group key has the format <code>key$value</code>, for example, <code>model$Claude Sonnet 5</code>. Costs that have no value for the key are in the group <code>key$</code>, for example, <code>model$</code>. Remove the <code>key$</code> prefix before you use a value in a <code>ProductAttributes</code> filter. Keys are case-sensitive: if you group by a key that doesn't exist, such as <code>Model</code>, all of your costs of supported services are in the group <code>Model$</code>.</p>
        billing_view_arn: <p>The Amazon Resource Name (ARN) that uniquely identifies a specific billing view. The ARN is used to specify which particular billing view you want to interact with or retrieve information from when making API calls related to Amazon Web Services Billing and Cost Management features. The BillingViewArn can be retrieved by calling the ListBillingViews API.</p>
        next_page_token: <p>The token to retrieve the next set of results. Amazon Web Services provides the token when the response from a previous call has more results than the maximum page size.</p>

    Raises:
        capo_cost_explorer.errors.bill_expiration_exception.BillExpirationException: <p>The requested report expired. Update the date interval and try again.</p>
        capo_cost_explorer.errors.billing_view_health_status_exception.BillingViewHealthStatusException: <p> The billing view status must be <code>HEALTHY</code> to perform this action. Try again when the status is <code>HEALTHY</code>. </p>
        capo_cost_explorer.errors.data_unavailable_exception.DataUnavailableException: <p>The requested data is unavailable.</p>
        capo_cost_explorer.errors.invalid_next_token_exception.InvalidNextTokenException: <p>The pagination token is invalid. Try again without a pagination token.</p>
        capo_cost_explorer.errors.limit_exceeded_exception.LimitExceededException: <p>You made too many calls in a short period of time. Try again later.</p>
        capo_cost_explorer.errors.request_changed_exception.RequestChangedException: <p>Your request parameters changed between pages. Try again with the old parameters or without a pagination token.</p>
        capo_cost_explorer.errors.resource_not_found_exception.ResourceNotFoundException: <p> The specified ARN in the request doesn't exist. </p>
        capo_cost_explorer.errors.UnknownServiceError: The service returned an error code this client does not model.
    """

    async def _handler(
        req: "AsyncOperationRequest[capo_cost_explorer.types.get_cost_and_usage_request.GetCostAndUsageRequest]",
    ) -> AsyncOperationResponse[
        "capo_cost_explorer.types.get_cost_and_usage_response.GetCostAndUsageResponse"
    ]:
        import capo_cost_explorer._operations.aws_insights_index_service.get_cost_and_usage

        (
            output,
            http_response,
        ) = await capo_cost_explorer._operations.aws_insights_index_service.get_cost_and_usage.async_get_cost_and_usage(
            req.options, req.input
        )
        return AsyncOperationResponse(output=output, response=http_response)

    interceptors_, options_ = self.operation_options(
        config_overrides, OperationLogging("GetCostAndUsage")
    )
    input_: capo_cost_explorer.types.get_cost_and_usage_request.GetCostAndUsageRequest = {
        "time_period": time_period,
        "granularity": granularity,
        "metrics": metrics,
    }
    if filter is not None:
        input_["filter"] = filter
    if group_by is not None:
        input_["group_by"] = group_by
    if billing_view_arn is not None:
        input_["billing_view_arn"] = billing_view_arn
    if next_page_token is not None:
        input_["next_page_token"] = next_page_token

    response = await aexecute_pipeline(
        AsyncOperationRequest(input=input_, options=options_),
        handler=_handler,
        interceptors=list(interceptors_),
    )
    await response.response.aclose()
    return response.output