Python

TypedDict for JSON API Shapes

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When you parse JSON, you want types — but creating a class for every payload is overkill. TypedDict gives you the static-checking benefits without the runtime overhead, and `total=False` marks every field optional.
Python
Raw
from typing import TypedDict, NotRequired

class Address(TypedDict):
    street: str
    city:   str
    zip:    str

class User(TypedDict):
    id:      int
    name:    str
    email:   str
    address: NotRequired[Address]   # Python 3.11+

def get_user(uid: int) -> User:
    return {"id": uid, "name": "Alice", "email": "a@x.com"}

u = get_user(42)
print(u["name"])              # type-checked: str
# u["age"]                    # mypy error: not in User
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.