Skip to content

Nested Model Example

Output models with nested structures. Links propagate into nested models.

Code

"""
Nested model example - output models with nested structures.
"""

from typing import Annotated

from pydantic import BaseModel
from semblance import FromInput, SemblanceAPI


class Address(BaseModel):
    street: str = ""
    city: Annotated[str, FromInput("city")]
    zip: str = ""


class UserWithAddress(BaseModel):
    name: Annotated[str, FromInput("name")]
    address: Address


class QueryWithCity(BaseModel):
    name: str = "alice"
    city: str = "NYC"


api = SemblanceAPI(seed=42)


@api.get(
    "/user",
    input=QueryWithCity,
    output=UserWithAddress,
    summary="Get user with address",
)
def user():
    """Returns user with nested address; city comes from query."""
    pass


app = api.as_fastapi()

Run

semblance run examples.nested.app:api --port 8000

Try

curl "http://127.0.0.1:8000/user?name=foo&city=Boston"

Example response (with seed=42):

{
  "name": "foo",
  "address": {
    "street": "HbolMJUevblAbkHClEQa",
    "city": "Boston",
    "zip": "PKriXrefSFPLBYtCRGSE"
  }
}

city comes from the query; street and zip are generated by Polyfactory.

Concepts

  • Nested modelsUserWithAddress contains Address
  • Links in nested fieldscity in Address uses FromInput("city")
  • Resolver traverses nested models to apply links