İçeriğe geç
Community

KONULARI KEŞFET

Editoryal yaklaşım

CoreTrailKit ile yeni mi tanışıyorsun?

Servislerini izle. Kanıtları elinin altında tut.

CoreTrailKit
Yazılara dön
REHBER/ AWS

Lambda: convert DynamoDB sets to JSON arrays

The DynamoDB read succeeds, but Lambda fails while returning the item. Inspect the Python types in the response: a DynamoDB string set can become a Python set that the response marshaller cannot encode.

Yazar: CoreTrailKit3 dk okuma

01

Separate the read from response serialization

A successful SDK read proves that the function obtained an item. The handler can still fail later while producing a JSON response. Look for the runtime’s marshal error and identify the specific field and type without printing a sensitive full record.

Our item contained an amount and a tags string set. The local runtime accepted the decimal value but rejected the Python set in the unfiltered item. This distinction prevented a numeric-serialization assumption from hiding the actual offending type.

02

Inspect the intended field’s type

Boto3’s Table resource returns Python-level representations rather than the low-level AttributeValue wrapper. Know which interface your code uses before applying a conversion. A string set and a list both represent collections, but they do not have the same type or ordering contract.

For a non-sensitive diagnostic, inspect only the field’s type name. In our local test, tags was a set. Python’s standard JSON type table is a useful baseline, but the exact Lambda runtime’s marshalling behavior should also be tested.

python · ÖRNEK
# Inspect only the selected field’s type, not the full item contents.
print(type(item.get("tags")).__name__)

03

Build a deliberate application response

Select only the fields the caller is meant to receive. For a string set, sorted creates a deterministic list for JSON output. Do not use this exact conversion for arbitrary binary values, mixed types, or an application where a different ordering contract is required.

The example represents amount as a string because that is the chosen response contract. Avoid indiscriminate default=str conversion: it can turn a set into a textual Python representation instead of an array and conceal other schema mistakes.

python · ÖRNEK
def build_response(item):
    return {
        "orderId": item["pk"],
        "amount": str(item["amount"]),
        "tags": sorted(item.get("tags", set())),
    }

04

Invoke the runtime and assert the response shape

Our local official-runtime invocation first returned Runtime.MarshalError when the handler returned the raw item. The corrected handler returned orderId as a string, amount as "13.25", and tags as ["new", "urgent"]. We checked the invocation result, not just json serialization in a different interpreter.

A focused application test can check that the mapped result contains the intended types and fields. Keep representative set and number values in that fixture so a later refactor cannot silently reintroduce the storage object into the public response.

python · ÖRNEK
from decimal import Decimal
import json

result = build_response({
    "pk": "order#1", "amount": Decimal("13.25"),
    "tags": {"urgent", "new"},
})
assert result["tags"] == ["new", "urgent"]
assert json.loads(json.dumps(result))["amount"] == "13.25"

05

Verify any integration envelope separately

A direct Lambda invocation and an API Gateway integration can expect different outer response shapes. After fixing the item’s JSON types, verify the particular integration’s status, headers, and body contract instead of assuming a direct handler response proves the whole HTTP path.

Keep the conversion near the application boundary and document its schema. The storage model can evolve independently, while callers continue receiving the intentional set-as-array and number representations that were tested.

Sınırları bil

Reproduced with official DynamoDB Local 3.3.2, Boto3 1.42.97, and the official Lambda Python 3.12 runtime/RIE. Returning a seeded item with a string set caused Runtime.MarshalError; an explicit response with sorted tags succeeded. No managed Lambda or API Gateway integration was deployed.

Kaynaklar ve ileri okuma

CoreTrailKit tarafından hazırlanan teknik yayın.

Bütün yazıları keşfet

KEŞFETMEYE DEVAM ET