0Pricing
FastAPI Backend Development Bootcamp · Lesson

Serialization with model_dump and Aliases

Control how Pydantic models convert to and from data using model_dump, field aliases, computed fields, and serialization options for clean API payloads.

Serialization with model_dump and Aliases is a free FastAPI Backend Development Bootcamp lesson on CoddyKit. This is lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the FastAPI Backend Development Bootcamp learning path, and your progress syncs across the web and the CoddyKit app. The FastAPI Backend Development Bootcamp course includes 4 lessons in total.

Serialization vs Validation

Pydantic does two jobs: validation (untrusted input becomes a typed model) and serialization (a model becomes a dict or JSON to send out). This lesson focuses on controlling the output side precisely.

model_dump Basics

In Pydantic v2, model_dump() turns a model into a dict and model_dump_json() into a JSON string.

from pydantic import BaseModel

class User(BaseModel):
    name: str
    age: int

u = User(name='Ada', age=36)
print(u.model_dump())
print(u.model_dump_json())

Including and Excluding Fields

Trim the output with include or exclude to hide internal or sensitive fields from a payload.

u.model_dump(exclude={'age'})
u.model_dump(include={'name'})

Dropping Defaults and None

Use exclude_none=True or exclude_defaults=True to produce leaner payloads that omit empty values.

class Profile(BaseModel):
    name: str
    bio: str | None = None

Profile(name='Ada').model_dump(exclude_none=True)

Field Aliases

External APIs often use names like userName while Python prefers user_name. An alias maps between them.

from pydantic import BaseModel, Field

class User(BaseModel):
    user_name: str = Field(alias='userName')

Serializing by Alias

By default model_dump uses the Python field names. Pass by_alias=True to output the alias names instead.

u = User(userName='ada')
print(u.model_dump())
print(u.model_dump(by_alias=True))

populate_by_name

Set model_config = ConfigDict(populate_by_name=True) to accept either the field name or the alias when parsing input, giving you flexibility on both ends.

from pydantic import ConfigDict

class User(BaseModel):
    model_config = ConfigDict(populate_by_name=True)
    user_name: str = Field(alias='userName')

Computed Fields

Expose derived values in the output with @computed_field. They appear in model_dump but are not part of the input.

from pydantic import computed_field

class Person(BaseModel):
    first: str
    last: str
    @computed_field
    @property
    def full(self) -> str:
        return self.first + ' ' + self.last

Custom Field Serializers

Use @field_serializer to control how a specific field is rendered, for example formatting a datetime or masking a secret.

from pydantic import field_serializer

class Account(BaseModel):
    card: str
    @field_serializer('card')
    def mask(self, v: str) -> str:
        return '****' + v[-4:]

Alias Mapping in Plain Python

The by_alias transform is just key renaming. Here is the concept without Pydantic.

data = {'user_name': 'ada', 'user_age': 36}
alias = {'user_name': 'userName', 'user_age': 'userAge'}
out = {alias[k]: v for k, v in data.items()}
print(out)

FastAPI Response Integration

FastAPI serializes return values through your response_model. Set response_model_by_alias and exclusion flags on the route to shape the JSON your API emits.

@app.get('/user', response_model=User, response_model_by_alias=True)
async def get_user():
    return User(user_name='ada')

Quick Check

Your model has user_name: str = Field(alias='userName'). What does model_dump(by_alias=True) produce for the key?

Recap

You mastered Pydantic serialization:

  • model_dump / model_dump_json with include, exclude, and exclude_none.
  • Aliases plus by_alias and populate_by_name.
  • Computed fields and custom field serializers.
  • Wiring it into FastAPI response models.

Frequently Asked Questions

Is the “Serialization with model_dump and Aliases” lesson free?

Yes — the full text of “Serialization with model_dump and Aliases” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the FastAPI Backend Development Bootcamp course, upgrade to CoddyKit PRO. The FastAPI Backend Development Bootcamp course includes 4 lessons in total.

What will I learn in “Serialization with model_dump and Aliases”?

Control how Pydantic models convert to and from data using model_dump, field aliases, computed fields, and serialization options for clean API payloads. You practise FastAPI Backend Development Bootcamp with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start FastAPI Backend Development Bootcamp?

No prior experience is required. FastAPI Backend Development Bootcamp on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Serialization with model_dump and Aliases” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this FastAPI Backend Development Bootcamp lesson?

Yes. Every FastAPI Backend Development Bootcamp lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Pydantic Field Validation & Validators
  2. Custom Data Types & Settings
  3. Nested Models & Recursive Structures
  4. Serialization with model_dump and Aliases
← Back to FastAPI Backend Development Bootcamp