Full answer
Real APIs often accept polymorphic payloads: a notification can be an email, an SMS or a push message; a payment can be a card, UPI or bank transfer. Each has different fields.
Plain union
payment: CardPayment | UpiPaymentPydantic tries each member and reports errors from all of them when none match, which is hard to read. It may also pick the wrong member when shapes overlap.
Discriminated union
class Card(BaseModel):
kind: Literal["card"]
number: str
class Upi(BaseModel):
kind: Literal["upi"]
vpa: str
class Order(BaseModel):
payment: Annotated[Card | Upi, Field(discriminator="kind")]How it works: Pydantic looks at kind, selects exactly one model and validates against it. Benefits:
- Clear errors:
{"kind": "upi"}withoutvpareports only the missingvpa, not errors forCardtoo. - An unknown tag gives one error listing the allowed tags (
union_tag_invalid). - Faster validation in the Rust core, with no trial and error.
- OpenAPI emits
oneOfplusdiscriminator.mapping, so generated clients create proper tagged types.
Variants
- Callable discriminators:
Discriminator(func)withTag("card")handles cases where the shape, not a field, decides the type, or where the tag is nested. - Nested discriminated unions work too.
- Models can share a base class holding common fields.
Design advice: use a stable, explicit tag from the start. Adding a new variant later is then a non-breaking change for clients that handle unknown kinds gracefully. Handling the parsed value is a clean match statement on the model type.
from typing import Annotated, Literal
from fastapi import FastAPI
from fastapi.testclient import TestClient
from pydantic import BaseModel, Field
app = FastAPI()
class Card(BaseModel):
kind: Literal["card"]
number: str = Field(min_length=12, max_length=19)
class Upi(BaseModel):
kind: Literal["upi"]
vpa: str = Field(pattern=r"^[\w.-]+@[\w]+$")
class NetBanking(BaseModel):
kind: Literal["netbanking"]
bank_code: str
Payment = Annotated[Card | Upi | NetBanking, Field(discriminator="kind")]
class FeePayment(BaseModel):
roll_no: str
amount: int = Field(gt=0)
payment: Payment
@app.post("/fees")
def pay(data: FeePayment):
match data.payment:
case Card():
how = "card ending " + data.payment.number[-4:]
case Upi():
how = "UPI " + data.payment.vpa
case NetBanking():
how = "bank " + data.payment.bank_code
return {"roll_no": data.roll_no, "paid_with": how}
c = TestClient(app)
base = {"roll_no": "BCA-17", "amount": 1500}
print(c.post("/fees", json={**base, "payment": {"kind": "upi", "vpa": "asha@okbank"}}).json())
print(c.post("/fees", json={**base, "payment": {"kind": "card", "number": "4111111111111111"}}).json())
err = c.post("/fees", json={**base, "payment": {"kind": "upi"}}).json()["detail"]
print([(e["loc"], e["type"]) for e in err])
err = c.post("/fees", json={**base, "payment": {"kind": "cash"}}).json()["detail"]
print([(e["loc"], e["type"]) for e in err])
print(c.get("/openapi.json").json()["components"]["schemas"]["FeePayment"]["properties"]["payment"]["discriminator"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'roll_no': 'BCA-17', 'paid_with': 'UPI asha@okbank'} {'roll_no': 'BCA-17', 'paid_with': 'card ending 1111'} [(['body', 'payment', 'upi', 'vpa'], 'missing')] [(['body', 'payment'], 'union_tag_invalid')] {'propertyName': 'kind', 'mapping': {'card': '#/components/schemas/Card', 'netbanking': '#/components/schemas/NetBanking', 'upi': '#/components/schemas/Upi'}}
Key points
- Literal tag field plus Field(discriminator=...)
- Pydantic validates only the matching member
- Errors are precise; validation is faster
- OpenAPI shows oneOf with a discriminator mapping
- Callable Discriminator and Tag cover shape-based cases
Common mistakes
- Using a plain union where shapes overlap and getting the wrong member
- Leaving out the Literal tag and relying on guesswork
- Changing tag values and breaking clients
- Doing isinstance chains instead of match on the parsed model
Follow-ups
- How would you add a new payment kind without breaking old clients?
- When do you need a callable Discriminator with Tag?
- How do generated TypeScript clients use the discriminator mapping?
Tips
- Contrast plain and discriminated unions with the error output
- Mention OpenAPI oneOf and client generation
- Show a match statement on the parsed type