Skip to content

put_item async

put_item(
    table_name: TableArn,
    item: PutItemInputAttributeMap,
    *,
    config_overrides: Optional[AsyncDynamoDBClientConfig] = None,
    expected: Optional[ExpectedAttributeMap] = None,
    return_values: Optional[ReturnValue] = None,
    return_consumed_capacity: Optional[ReturnConsumedCapacity] = None,
    return_item_collection_metrics: Optional[ReturnItemCollectionMetrics] = None,
    conditional_operator: Optional[ConditionalOperator] = None,
    condition_expression: Optional[ConditionExpression] = None,
    expression_attribute_names: Optional[ExpressionAttributeNameMap] = None,
    expression_attribute_values: Optional[ExpressionAttributeValueMap] = None,
    return_values_on_condition_check_failure: Optional[
        ReturnValuesOnConditionCheckFailure
    ] = None,
) -> PutItemOutput

Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values. You can return the item's attribute values in the same operation, using the ReturnValues parameter.

When you add an item, the primary key attributes are the only required attributes.

Empty String and Binary attribute values are allowed. Attribute values of type String and Binary must have a length greater than zero if the attribute is used as a key attribute for a table or index. Set type attributes cannot be empty.

Invalid Requests with empty values will be rejected with a ValidationException exception.

To prevent a new item from replacing an existing item, use a conditional expression that contains the attribute_not_exists function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the attribute_not_exists function will only succeed if no matching item exists.

To determine whether PutItem overwrote an existing item, use ReturnValues set to ALL_OLD. If the response includes the Attributes element, an existing item was overwritten.

For more information about PutItem, see Working with Items in the Amazon DynamoDB Developer Guide.

Parameters:

  • table_name (TableArn) –

    The name of the table to contain the item. You can also provide the Amazon Resource Name (ARN) of the table in this parameter.

  • item (PutItemInputAttributeMap) –

    A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item.

    You must provide all of the attributes for the primary key. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide both values for both the partition key and the sort key.

    If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition.

    If the table has vector indexes, the following validations apply to write operations. A violation of any of these constraints results in a ValidationException:

    • The vector attribute must be a list of numbers with dimensions matching the index configuration.

    • Vector values must fit in 32-bit IEEE-754 floating point format (f32).

    • Partition key and inline filter attributes defined in the search schema must have data types matching the index schema definition.

    Empty String and Binary attribute values are allowed. Attribute values of type String and Binary must have a length greater than zero if the attribute is used as a key attribute for a table or index.

    For more information about primary keys, see Primary Key in the Amazon DynamoDB Developer Guide.

    Each element in the Item map is an AttributeValue object.

  • expected (Optional[ExpectedAttributeMap], default: None ) –

    This is a legacy parameter. Use ConditionExpression instead. For more information, see Expected in the Amazon DynamoDB Developer Guide.

  • return_values (Optional[ReturnValue], default: None ) –

    Use ReturnValues if you want to get the item attributes as they appeared before they were updated with the PutItem request. For PutItem, the valid values are:

    • NONE - If ReturnValues is not specified, or if its value is NONE, then nothing is returned. (This setting is the default for ReturnValues.)

    • ALL_OLD - If PutItem overwrote an attribute name-value pair, then the content of the old item is returned.

    The values returned are strongly consistent.

    There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.

    The ReturnValues parameter is used by several DynamoDB operations; however, PutItem does not recognize any values other than NONE or ALL_OLD.

  • return_item_collection_metrics (Optional[ReturnItemCollectionMetrics], default: None ) –

    Determines whether item collection metrics are returned. If set to SIZE, the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to NONE (the default), no statistics are returned.

  • conditional_operator (Optional[ConditionalOperator], default: None ) –

    This is a legacy parameter. Use ConditionExpression instead. For more information, see ConditionalOperator in the Amazon DynamoDB Developer Guide.

  • condition_expression (Optional[ConditionExpression], default: None ) –

    A condition that must be satisfied in order for a conditional PutItem operation to succeed.

    An expression can contain any of the following:

    • Functions: attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size

      These function names are case-sensitive.

    • Comparison operators: = | <> | < | > | <= | >= | BETWEEN | IN

    • Logical operators: AND | OR | NOT

    For more information on condition expressions, see Condition Expressions in the Amazon DynamoDB Developer Guide.

  • expression_attribute_names (Optional[ExpressionAttributeNameMap], default: None ) –

    One or more substitution tokens for attribute names in an expression. The following are some use cases for using ExpressionAttributeNames:

    • To access an attribute whose name conflicts with a DynamoDB reserved word.

    • To create a placeholder for repeating occurrences of an attribute name in an expression.

    • To prevent special characters in an attribute name from being misinterpreted in an expression.

    Use the # character in an expression to dereference an attribute name. For example, consider the following attribute name:

    • Percentile

    The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see Reserved Words in the Amazon DynamoDB Developer Guide). To work around this, you could specify the following for ExpressionAttributeNames:

    • {"#P":"Percentile"}

    You could then use this substitution in an expression, as in this example:

    • #P = :val

    Tokens that begin with the : character are expression attribute values, which are placeholders for the actual value at runtime.

    For more information on expression attribute names, see Specifying Item Attributes in the Amazon DynamoDB Developer Guide.

  • expression_attribute_values (Optional[ExpressionAttributeValueMap], default: None ) –

    One or more values that can be substituted in an expression.

    Use the : (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the ProductStatus attribute was one of the following:

    Available | Backordered | Discontinued

    You would first need to specify ExpressionAttributeValues as follows:

    { ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} }

    You could then use these values in an expression, such as this:

    ProductStatus IN (:avail, :back, :disc)

    For more information on expression attribute values, see Condition Expressions in the Amazon DynamoDB Developer Guide.

  • return_values_on_condition_check_failure (Optional[ReturnValuesOnConditionCheckFailure], default: None ) –

    An optional parameter that returns the item attributes for a PutItem operation that failed a condition check.

    There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.

Raises:

  • ConditionalCheckFailedException –

    A condition specified in the operation failed to be evaluated.

  • InternalServerError –

    An error occurred on the server side.

  • ItemCollectionSizeLimitExceededException –

    An item collection is too large. This exception is only returned for tables that have one or more local secondary indexes.

  • ProvisionedThroughputExceededException –

    The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception. The Amazon Web Services SDKs for DynamoDB automatically retry requests that receive this exception. Your request is eventually successful, unless your retry queue is too large to finish. Reduce the frequency of requests and use exponential backoff. For more information, go to Error Retries and Exponential Backoff in the Amazon DynamoDB Developer Guide.

  • ReplicatedWriteConflictException –

    The request was rejected because one or more items in the request are being modified by a request in another Region.

  • RequestLimitExceeded –

    Throughput exceeds the current throughput quota for your account. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception. Contact Amazon Web Services Support to request a quota increase.

  • ResourceNotFoundException –

    The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be ACTIVE.

  • ThrottlingException –

    The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the ThrottlingReason field in the returned exception.

  • TransactionConflictException –

    Operation was rejected because there is an ongoing transaction for the item.

  • UnknownServiceError –

    The service returned an error code this client does not model.

Examples:

To add an item to a table This example adds a new item to the Music table.

>>> await client.put_item(table_name='Music', item={'AlbumTitle': {'S': 'Somewhat Famous'}, 'SongTitle': {'S': 'Call Me Today'}, 'Artist': {'S': 'No One You Know'}}, return_consumed_capacity='TOTAL')
Source code in docs_src/capo_dynamodb/_services/async_dynamo_db.py
async def put_item(
    self,
    table_name: "capo_dynamodb.types.table_arn.TableArn",
    item: "capo_dynamodb.types.put_item_input_attribute_map.PutItemInputAttributeMap",
    *,
    config_overrides: Optional[AsyncDynamoDBClientConfig] = None,
    expected: Optional[
        "capo_dynamodb.types.expected_attribute_map.ExpectedAttributeMap"
    ] = None,
    return_values: Optional["capo_dynamodb.types.return_value.ReturnValue"] = None,
    return_consumed_capacity: Optional[
        "capo_dynamodb.types.return_consumed_capacity.ReturnConsumedCapacity"
    ] = None,
    return_item_collection_metrics: Optional[
        "capo_dynamodb.types.return_item_collection_metrics.ReturnItemCollectionMetrics"
    ] = None,
    conditional_operator: Optional[
        "capo_dynamodb.types.conditional_operator.ConditionalOperator"
    ] = None,
    condition_expression: Optional[
        "capo_dynamodb.types.condition_expression.ConditionExpression"
    ] = None,
    expression_attribute_names: Optional[
        "capo_dynamodb.types.expression_attribute_name_map.ExpressionAttributeNameMap"
    ] = None,
    expression_attribute_values: Optional[
        "capo_dynamodb.types.expression_attribute_value_map.ExpressionAttributeValueMap"
    ] = None,
    return_values_on_condition_check_failure: Optional[
        "capo_dynamodb.types.return_values_on_condition_check_failure.ReturnValuesOnConditionCheckFailure"
    ] = None,
) -> "capo_dynamodb.types.put_item_output.PutItemOutput":
    """<p>Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item. You can perform a conditional put operation (add a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values. You can return the item's attribute values in the same operation, using the <code>ReturnValues</code> parameter.</p> <p>When you add an item, the primary key attributes are the only required attributes. </p> <p>Empty String and Binary attribute values are allowed. Attribute values of type String and Binary must have a length greater than zero if the attribute is used as a key attribute for a table or index. Set type attributes cannot be empty. </p> <p>Invalid Requests with empty values will be rejected with a <code>ValidationException</code> exception.</p> <note> <p>To prevent a new item from replacing an existing item, use a conditional expression that contains the <code>attribute_not_exists</code> function with the name of the attribute being used as the partition key for the table. Since every record must contain that attribute, the <code>attribute_not_exists</code> function will only succeed if no matching item exists.</p> </note> <note> <p>To determine whether <code>PutItem</code> overwrote an existing item, use <code>ReturnValues</code> set to <code>ALL_OLD</code>. If the response includes the <code>Attributes</code> element, an existing item was overwritten.</p> </note> <p>For more information about <code>PutItem</code>, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/WorkingWithItems.html">Working with Items</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>

    Args:
        table_name: <p>The name of the table to contain the item. You can also provide the Amazon Resource Name (ARN) of the table in this parameter.</p>
        item: <p>A map of attribute name/value pairs, one for each attribute. Only the primary key attributes are required; you can optionally provide other attribute name-value pairs for the item.</p> <p>You must provide all of the attributes for the primary key. For example, with a simple primary key, you only need to provide a value for the partition key. For a composite primary key, you must provide both values for both the partition key and the sort key.</p> <p>If you specify any attributes that are part of an index key, then the data types for those attributes must match those of the schema in the table's attribute definition.</p> <p>If the table has vector indexes, the following validations apply to write operations. A violation of any of these constraints results in a <code>ValidationException</code>:</p> <ul> <li> <p>The vector attribute must be a list of numbers with dimensions matching the index configuration.</p> </li> <li> <p>Vector values must fit in 32-bit IEEE-754 floating point format (f32).</p> </li> <li> <p>Partition key and inline filter attributes defined in the search schema must have data types matching the index schema definition.</p> </li> </ul> <p>Empty String and Binary attribute values are allowed. Attribute values of type String and Binary must have a length greater than zero if the attribute is used as a key attribute for a table or index.</p> <p>For more information about primary keys, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.PrimaryKey">Primary Key</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p> <p>Each element in the <code>Item</code> map is an <code>AttributeValue</code> object.</p>
        expected: <p>This is a legacy parameter. Use <code>ConditionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.Expected.html">Expected</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        return_values: <p>Use <code>ReturnValues</code> if you want to get the item attributes as they appeared before they were updated with the <code>PutItem</code> request. For <code>PutItem</code>, the valid values are:</p> <ul> <li> <p> <code>NONE</code> - If <code>ReturnValues</code> is not specified, or if its value is <code>NONE</code>, then nothing is returned. (This setting is the default for <code>ReturnValues</code>.)</p> </li> <li> <p> <code>ALL_OLD</code> - If <code>PutItem</code> overwrote an attribute name-value pair, then the content of the old item is returned.</p> </li> </ul> <p>The values returned are strongly consistent.</p> <p>There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.</p> <note> <p>The <code>ReturnValues</code> parameter is used by several DynamoDB operations; however, <code>PutItem</code> does not recognize any values other than <code>NONE</code> or <code>ALL_OLD</code>.</p> </note>
        return_item_collection_metrics: <p>Determines whether item collection metrics are returned. If set to <code>SIZE</code>, the response includes statistics about item collections, if any, that were modified during the operation are returned in the response. If set to <code>NONE</code> (the default), no statistics are returned.</p>
        conditional_operator: <p>This is a legacy parameter. Use <code>ConditionExpression</code> instead. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/LegacyConditionalParameters.ConditionalOperator.html">ConditionalOperator</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        condition_expression: <p>A condition that must be satisfied in order for a conditional <code>PutItem</code> operation to succeed.</p> <p>An expression can contain any of the following:</p> <ul> <li> <p>Functions: <code>attribute_exists | attribute_not_exists | attribute_type | contains | begins_with | size</code> </p> <p>These function names are case-sensitive.</p> </li> <li> <p>Comparison operators: <code>= | <> | < | > | <= | >= | BETWEEN | IN </code> </p> </li> <li> <p> Logical operators: <code>AND | OR | NOT</code> </p> </li> </ul> <p>For more information on condition expressions, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Condition Expressions</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        expression_attribute_names: <p>One or more substitution tokens for attribute names in an expression. The following are some use cases for using <code>ExpressionAttributeNames</code>:</p> <ul> <li> <p>To access an attribute whose name conflicts with a DynamoDB reserved word.</p> </li> <li> <p>To create a placeholder for repeating occurrences of an attribute name in an expression.</p> </li> <li> <p>To prevent special characters in an attribute name from being misinterpreted in an expression.</p> </li> </ul> <p>Use the <b>#</b> character in an expression to dereference an attribute name. For example, consider the following attribute name:</p> <ul> <li> <p> <code>Percentile</code> </p> </li> </ul> <p>The name of this attribute conflicts with a reserved word, so it cannot be used directly in an expression. (For the complete list of reserved words, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html">Reserved Words</a> in the <i>Amazon DynamoDB Developer Guide</i>). To work around this, you could specify the following for <code>ExpressionAttributeNames</code>:</p> <ul> <li> <p> <code>{"#P":"Percentile"}</code> </p> </li> </ul> <p>You could then use this substitution in an expression, as in this example:</p> <ul> <li> <p> <code>#P = :val</code> </p> </li> </ul> <note> <p>Tokens that begin with the <b>:</b> character are <i>expression attribute values</i>, which are placeholders for the actual value at runtime.</p> </note> <p>For more information on expression attribute names, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html">Specifying Item Attributes</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        expression_attribute_values: <p>One or more values that can be substituted in an expression.</p> <p>Use the <b>:</b> (colon) character in an expression to dereference an attribute value. For example, suppose that you wanted to check whether the value of the <i>ProductStatus</i> attribute was one of the following: </p> <p> <code>Available | Backordered | Discontinued</code> </p> <p>You would first need to specify <code>ExpressionAttributeValues</code> as follows:</p> <p> <code>{ ":avail":{"S":"Available"}, ":back":{"S":"Backordered"}, ":disc":{"S":"Discontinued"} }</code> </p> <p>You could then use these values in an expression, such as this:</p> <p> <code>ProductStatus IN (:avail, :back, :disc)</code> </p> <p>For more information on expression attribute values, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.SpecifyingConditions.html">Condition Expressions</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        return_values_on_condition_check_failure: <p>An optional parameter that returns the item attributes for a <code>PutItem</code> operation that failed a condition check.</p> <p>There is no additional cost associated with requesting a return value aside from the small network and processing overhead of receiving a larger response. No read capacity units are consumed.</p>

    Raises:
        capo_dynamodb.errors.conditional_check_failed_exception.ConditionalCheckFailedException: <p>A condition specified in the operation failed to be evaluated.</p>
        capo_dynamodb.errors.internal_server_error.InternalServerError: <p>An error occurred on the server side.</p>
        capo_dynamodb.errors.invalid_endpoint_exception.InvalidEndpointException
        capo_dynamodb.errors.item_collection_size_limit_exceeded_exception.ItemCollectionSizeLimitExceededException: <p>An item collection is too large. This exception is only returned for tables that have one or more local secondary indexes.</p>
        capo_dynamodb.errors.provisioned_throughput_exceeded_exception.ProvisionedThroughputExceededException: <p>The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception. The Amazon Web Services SDKs for DynamoDB automatically retry requests that receive this exception. Your request is eventually successful, unless your retry queue is too large to finish. Reduce the frequency of requests and use exponential backoff. For more information, go to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html#Programming.Errors.RetryAndBackoff">Error Retries and Exponential Backoff</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p>
        capo_dynamodb.errors.replicated_write_conflict_exception.ReplicatedWriteConflictException: <p>The request was rejected because one or more items in the request are being modified by a request in another Region. </p>
        capo_dynamodb.errors.request_limit_exceeded.RequestLimitExceeded: <p>Throughput exceeds the current throughput quota for your account. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception. Contact <a href="https://aws.amazon.com/support">Amazon Web Services Support</a> to request a quota increase.</p>
        capo_dynamodb.errors.resource_not_found_exception.ResourceNotFoundException: <p>The operation tried to access a nonexistent table or index. The resource might not be specified correctly, or its status might not be <code>ACTIVE</code>.</p>
        capo_dynamodb.errors.throttling_exception.ThrottlingException: <p>The request was denied due to request throttling. For detailed information about why the request was throttled and the ARN of the impacted resource, find the <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_ThrottlingReason.html">ThrottlingReason</a> field in the returned exception.</p>
        capo_dynamodb.errors.transaction_conflict_exception.TransactionConflictException: <p>Operation was rejected because there is an ongoing transaction for the item.</p>
        capo_dynamodb.errors.UnknownServiceError: The service returned an error code this client does not model.

    Examples:
        To add an item to a table
        This example adds a new item to the Music table.

        >>> await client.put_item(table_name='Music', item={'AlbumTitle': {'S': 'Somewhat Famous'}, 'SongTitle': {'S': 'Call Me Today'}, 'Artist': {'S': 'No One You Know'}}, return_consumed_capacity='TOTAL')
    """

    async def _handler(
        req: "AsyncOperationRequest[capo_dynamodb.types.put_item_input.PutItemInput]",
    ) -> AsyncOperationResponse[
        "capo_dynamodb.types.put_item_output.PutItemOutput"
    ]:
        import capo_dynamodb._operations.dynamo_db_20120810.put_item

        (
            output,
            http_response,
        ) = await capo_dynamodb._operations.dynamo_db_20120810.put_item.async_put_item(
            req.options, req.input
        )
        return AsyncOperationResponse(output=output, response=http_response)

    interceptors_, options_ = self.operation_options(
        config_overrides, OperationLogging("PutItem")
    )
    input_: capo_dynamodb.types.put_item_input.PutItemInput = {
        "table_name": table_name,
        "item": item,
    }
    if expected is not None:
        input_["expected"] = expected
    if return_values is not None:
        input_["return_values"] = return_values
    if return_consumed_capacity is not None:
        input_["return_consumed_capacity"] = return_consumed_capacity
    if return_item_collection_metrics is not None:
        input_["return_item_collection_metrics"] = return_item_collection_metrics
    if conditional_operator is not None:
        input_["conditional_operator"] = conditional_operator
    if condition_expression is not None:
        input_["condition_expression"] = condition_expression
    if expression_attribute_names is not None:
        input_["expression_attribute_names"] = expression_attribute_names
    if expression_attribute_values is not None:
        input_["expression_attribute_values"] = expression_attribute_values
    if return_values_on_condition_check_failure is not None:
        input_["return_values_on_condition_check_failure"] = (
            return_values_on_condition_check_failure
        )

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