Lesson 14.7 · 7 of 8 · 6 min read · Reviewed 24 Nov 2026
Mapping typed models to response schemas
By the end, you can
- Generate a response schema from a typed model instead of writing it by hand.
- Map common types to JSON Schema and avoid the mappings that break strict modes.
In 18.1 you wrote a JSON schema by hand. In a real codebase the same shape also lives in your code, as a class or a type. Keeping two copies in step by hand is how bugs creep in: someone adds a field to the class and forgets the schema, and the model never fills it.
The fix is one source of truth. Define the shape as a typed model, generate the schema from it, and parse the model’s reply back into that type.
typed model --> JSON Schema --> request --> reply JSON --> parse into typed model
^ |
+-------------------- one definition --------------------+
Popular tools do this for you. In Python, Pydantic models have a method that returns a JSON Schema. In TypeScript, Zod schemas can be converted to JSON Schema. Several provider SDKs accept these models directly and parse the reply for you. Without a library, you can walk a Python dataclass’s fields and type hints yourself, which is exactly what this lesson’s lab does.
The mapping
| In code (Python / TypeScript) | JSON Schema |
|---|---|
str / string |
{"type": "string"} |
int |
{"type": "integer"} |
float / number |
{"type": "number"} |
bool / boolean |
{"type": "boolean"} |
list[str] / string[] |
{"type": "array", "items": {"type": "string"}} |
Literal["low", "high"], an Enum / a union of literals |
{"type": "string", "enum": ["low", "high"]} |
Optional[str] / string | null |
{"type": ["string", "null"]} or an anyOf with null |
| A nested model | A nested object, or a $ref into $defs |
| A field description | "description": "..." |
Worked example, as a dataclass:
@dataclass
class Ticket:
customer_name: str
priority: Literal["low", "medium", "high"]
order_id: Optional[str] # null if no order ID appears
items: list[str]
The generated schema has four properties, all four in required, priority as an enum and order_id as ["string", "null"]. That is the schema from 18.1, but now it cannot drift from the class.
Where the mapping bites
- Defaults mean “not required”.
notes: Optional[str] = Noneis usually generated as optional. Strict modes (14.2) want every field required, so drop the default and keep the nullable type. $refand$defs. Nested models are often emitted as references. Check your provider supports them, or inline the nested object.- Unsupported constraints. A
max_lengthor a numeric range in your model may be emitted as a keyword the strict mode ignores. Keep validating those in code after parsing. - Extra properties. Set the object to forbid extra fields, so the schema has
"additionalProperties": false. - Descriptions get lost. A comment in code is not a description. Use the library’s field description so it reaches the model.
When to use it
Generate the schema whenever the output feeds code you own. Commit a snapshot of the generated schema, or test it in CIContinuous integration (CI): Automatically building and testing code on every change, usually in a hosted pipeline., so a change to the type shows up as a schema diff in review (15.4). Hand-written schemas are fine for a quick prototype or a one-off script.
Key points
- Define the output shape once as a typed model, generate the JSON Schema from it, and parse the reply back into the same type.
- Each type maps to a schema keyword: str to string, int to integer, Optional to a nullable type, Literal or Enum to enum, list to array.
- Defaults and optional fields often become 'not required', which strict modes reject; make the field required and nullable instead.
Generate a JSON Schema from a dataclass
Build a response schema from a typed Python model so the type and the schema can never drift apart.
You will have: A to_schema function that maps a dataclass (with Literal, Optional, list and nested types) to a strict-friendly JSON Schema, plus a parser back into the dataclass.
Steps
- Read the Ticket and Customer dataclasses in the starter. Pydantic and Zod are not available here, so you will use the standard library.
- Complete type_schema for str, int, float, bool, Literal, Optional, list and nested dataclasses.
- Complete to_schema so every field is in required, additionalProperties is false, and fields with defaults are reported as warnings.
- Parse a sample reply back into a Ticket with from_dict and print it.
Done when
- priority becomes an enum and order_id becomes ["string", "null"].
- The nested Customer becomes a nested object with its own required list.
- The field with a default is reported: 'warning: notes has a default'.
- The sample reply parses into a Ticket instance.
Open in the Playground No API key needed.
Starter code (Python)
import json
from dataclasses import dataclass, fields, is_dataclass, MISSING
from typing import Literal, Optional, get_type_hints, get_origin, get_args, Union
@dataclass
class Customer:
name: str
email: Optional[str]
@dataclass
class Ticket:
customer: Customer
priority: Literal["low", "medium", "high"]
order_id: Optional[str]
items: list[str]
notes: Optional[str] = None
PRIMITIVES = {str: "string", int: "integer", float: "number", bool: "boolean"}
def type_schema(tp):
# TODO: handle each case and return a schema dict:
# str/int/float/bool -> {"type": ...}
# Literal[...] -> {"type": "string", "enum": [...]}
# Optional[X] (Union with NoneType) -> X's schema with "type": [X_type, "null"]
# list[X] -> {"type": "array", "items": type_schema(X)}
# a dataclass -> to_schema(tp)
return {"type": "string"}
def to_schema(cls, warnings=None):
hints = get_type_hints(cls)
props = {}
for f in fields(cls):
props[f.name] = type_schema(hints[f.name])
# TODO: if f.default is not MISSING, add f"warning: {f.name} has a default" to warnings
# TODO: return an object schema with properties, required (all names) and additionalProperties False
return {"type": "object", "properties": props}
def from_dict(cls, data):
# TODO: build cls(**data), turning nested dicts into their dataclass first.
return data
warnings = []
schema = to_schema(Ticket, warnings)
print(json.dumps(schema, indent=1))
for w in warnings:
print(w)
reply = {"customer": {"name": "Priya", "email": None}, "priority": "high", "order_id": "58213", "items": ["lid"], "notes": None}
print(from_dict(Ticket, reply))
Show a solution
import json
from dataclasses import dataclass, fields, is_dataclass, MISSING
from typing import Literal, Optional, get_type_hints, get_origin, get_args, Union
@dataclass
class Customer:
name: str
email: Optional[str]
@dataclass
class Ticket:
customer: Customer
priority: Literal["low", "medium", "high"]
order_id: Optional[str]
items: list[str]
notes: Optional[str] = None
PRIMITIVES = {str: "string", int: "integer", float: "number", bool: "boolean"}
def type_schema(tp, warnings=None):
if tp in PRIMITIVES:
return {"type": PRIMITIVES[tp]}
origin, args = get_origin(tp), get_args(tp)
if origin is Literal:
return {"type": "string", "enum": list(args)}
if origin is Union and type(None) in args:
inner = [a for a in args if a is not type(None)][0]
s = type_schema(inner, warnings)
s["type"] = [s["type"], "null"]
return s
if origin is list:
return {"type": "array", "items": type_schema(args[0], warnings)}
if is_dataclass(tp):
return to_schema(tp, warnings)
raise TypeError(f"no mapping for {tp}")
def to_schema(cls, warnings=None):
hints = get_type_hints(cls)
props = {}
for f in fields(cls):
props[f.name] = type_schema(hints[f.name], warnings)
if f.default is not MISSING and warnings is not None:
warnings.append(f"warning: {f.name} has a default; strict modes want it required, so drop the default")
return {"type": "object", "properties": props, "required": [f.name for f in fields(cls)], "additionalProperties": False}
def from_dict(cls, data):
hints = get_type_hints(cls)
kwargs = {}
for f in fields(cls):
value = data[f.name]
if is_dataclass(hints[f.name]) and isinstance(value, dict):
value = from_dict(hints[f.name], value)
kwargs[f.name] = value
return cls(**kwargs)
warnings = []
schema = to_schema(Ticket, warnings)
print(json.dumps(schema, indent=1))
for w in warnings:
print(w)
reply = {"customer": {"name": "Priya", "email": None}, "priority": "high", "order_id": "58213", "items": ["lid"], "notes": None}
print(from_dict(Ticket, reply))