This rule raises an issue when AWS Lambda handlers return values that are not JSON serializable.

Why is this an issue?

For synchronous AWS Lambda invocations, like via API Gateway or direct SDK calls, the value returned by the handler is automatically serialized into a JSON string before being sent back in the response. If the return value contains objects that are not native JSON types like datetime objects, sets, or custom class instances, the serialization will fail, causing a TypeError. This will prevent the Lambda from returning a valid response to the client.

How to fix it

Convert non-JSON-serializable objects to their string representation or to JSON-serializable types before returning them:

See the following examples for more details on how to handle custom classes:

import json
import dataclasses

# A custom class representing a user
@dataclasses.dataclass
class User:
    name: str
    age: int

    def to_dict(self) -> dict:
        return { "name": self.name, "age": self.age }

user = User("Alice", 30)

# Method 1: Using __dict__ field
json.dumps(user.__dict__)

# Method 2: Using dataclasses.asdict()
json.dumps(dataclasses.asdict(user))

# Method 3: Using custom to_dict() method
json.dumps(user.to_dict())

Code examples

Noncompliant code example

import datetime

def lambda_handler(event, context):
    return {
        "message": "Request processed successfully",
        "timestamp": datetime.datetime.now()  # Noncompliant: not JSON serializable
    }

Compliant solution

import datetime

def lambda_handler(event, context):
    return {
        "message": "Request processed successfully",
        "timestamp": datetime.datetime.now().isoformat()  # Compliant: converted to string
    }

Resources

Documentation