📖 Scenario: You are building a simple FastAPI app to manage user data. You want to use Pydantic models to define the shape of the user data clearly and safely.
🎯 Goal: Create a Pydantic model called User with specific fields, then use it in a FastAPI endpoint to accept user data.
📋 What You'll Learn
Create a Pydantic model named User with fields id (int), name (str), and email (str).
Add a variable app as a FastAPI instance.
Create a POST endpoint /users/ that accepts a User model as input.
Return the received User data as JSON in the response.
💡 Why This Matters
🌍 Real World
Using Pydantic models in FastAPI helps create APIs that clearly define what data they expect and return. This reduces bugs and improves communication between frontend and backend.
💼 Career
Many backend developer jobs require knowledge of FastAPI and Pydantic for building modern, fast, and reliable APIs.
Progress0 / 4 steps
1
Create the Pydantic model
Create a Pydantic model called User with these exact fields and types: id as int, name as str, and email as str. Import BaseModel from pydantic.
FastAPI
Hint
Remember to import BaseModel from pydantic and create a class User that inherits from it.
2
Create the FastAPI app instance
Import FastAPI from fastapi and create a variable called app that is an instance of FastAPI().
FastAPI
Hint
Use app = FastAPI() to create the app instance.
3
Create the POST endpoint to accept User data
Create a POST endpoint at path /users/ using the @app.post decorator. Define a function called create_user that takes a parameter user of type User. The function should return the user object.
FastAPI
Hint
Use @app.post('/users/') and define a function with parameter user: User that returns user.
4
Complete the FastAPI app with Pydantic model usage
Ensure the full code includes the import statements, the User model, the app instance, and the POST endpoint /users/ that accepts and returns a User object.
FastAPI
Hint
Check that all parts are included: imports, model, app instance, and endpoint.
Practice
(1/5)
1. What is the main purpose of a Pydantic model in FastAPI?
easy
A. To validate and organize data automatically
B. To create HTML templates
C. To manage database connections
D. To handle user authentication
Solution
Step 1: Understand Pydantic model role
Pydantic models are designed to check and organize data by validating types and structure. This matches "To validate and organize data automatically".
Final Answer:
To validate and organize data automatically -> Option A
Quick Check:
Pydantic = Data validation and organization [OK]
Hint: Pydantic models are for data validation, not UI or DB [OK]
Common Mistakes:
Confusing Pydantic with template engines
Thinking Pydantic manages databases
Assuming Pydantic handles authentication
2. Which of the following is the correct way to define a simple Pydantic model with a required string field name?
easy
A. class User:
name = str
B. def User():
name: str
C. class User(BaseModel):
name: str
D. class User(BaseModel):
name = 'str'
Solution
Step 1: Recall Pydantic model syntax
A Pydantic model must inherit from BaseModel and define fields with type annotations like class User(BaseModel):
name: str. Other options miss inheritance or use assignment instead of type annotation.
Final Answer:
class User(BaseModel):\n name: str -> Option C
Quick Check:
BaseModel + type annotation = correct model [OK]
Hint: Use BaseModel and type annotations for fields [OK]
Common Mistakes:
Not inheriting from BaseModel
Using assignment instead of type annotation
Defining model as a function
3. Given this Pydantic model and code:
from pydantic import BaseModel
class Item(BaseModel):
id: int
name: str
item = Item(id='10', name='Book')
print(item.id, type(item.id))
What will be the output?
medium
A. 10
B. '10'
C. Error: id must be int
D. 10
Solution
Step 1: Understand Pydantic type coercion
Pydantic automatically converts compatible types like string '10' to int 10, so print(item.id, type(item.id)) outputs 10 <class 'int'>.
Hint: Pydantic converts strings to int if possible [OK]
Common Mistakes:
Expecting a type error for string input
Assuming no conversion happens
Confusing output type with input type
4. What is wrong with this Pydantic model definition?
from pydantic import BaseModel
class Product(BaseModel):
price: float = 'free'
medium
A. Class name should be lowercase
B. Default value 'free' is a string, but price expects a float
C. Missing import for BaseModel
D. Field price must be an integer
Solution
Step 1: Check field type and default value
price: float = 'free' is invalid because the string 'free' cannot be converted to float, causing a validation error.
Final Answer:
Default value 'free' is a string, but price expects a float -> Option B
Quick Check:
Field type and default must match [OK]
Hint: Default values must match field types exactly [OK]
Common Mistakes:
Using wrong default value types
Ignoring type mismatch errors
Thinking class names must be lowercase
5. You want to create a Pydantic model User with an optional age field that defaults to 18 if not provided. Which is the correct way?
hard
A. class User(BaseModel):
age: int = 18
B. class User(BaseModel):
age: Optional[int]
C. class User(BaseModel):
age: int = None
D. class User(BaseModel):
age: int
Solution
Step 1: Understand optional field with default
To make age optional with default 18, use age: int = 18. age: Optional[int] lacks default (required but allows None), age: int = None is invalid (None not int), age: int requires a value.
Final Answer:
class User(BaseModel):\n age: int = 18 -> Option A
Quick Check:
Default value makes field optional [OK]
Hint: Assign default value to make field optional [OK]
Common Mistakes:
Using Optional without default
Assigning None to non-optional int
Forgetting to assign default value
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.