用于请求体的 Pydantic 模型
使用 Pydantic 为传入的 POST、PUT 和 DELETE 请求定义数据模式,确保可靠的数据验证。
用于请求体的 Pydantic 模型 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
API Request Bodies
When you send data to an API, like creating a new user or an item, that data is often sent in the request body.
For example, a request to create a new product might include its name, price, and description. Ensuring this incoming data is correct and valid is crucial for your application's stability and security.
Why Validate Request Data?
Validating incoming data is essential for several reasons:
- Data Integrity: Ensures your database receives only correctly formatted and meaningful information.
- Security: Prevents malicious or malformed data from causing errors or vulnerabilities.
- User Experience: Provides clear error messages to users when their input is incorrect.
- Code Reliability: Reduces bugs by guaranteeing that your application logic operates on expected data types.
Meet Pydantic
Pydantic is a Python library that provides data validation and settings management using Python type hints. It's incredibly fast and integrates seamlessly with FastAPI.
FastAPI uses Pydantic behind the scenes to:
- Parse request bodies into Python objects.
- Validate data types and constraints.
- Generate clear error messages if validation fails.
Creating Your First Pydantic Model
To define a data structure for your request body, you create a class that inherits from Pydantic's BaseModel. You then declare fields using standard Python type hints.
This model acts as a schema, specifying what data your API expects.
Pydantic Model in Action
Let's define a simple Item model. Notice how we specify name as a string and price as a float. We'll also show how it handles validation!
from pydantic import BaseModel, ValidationError
class Item(BaseModel):
name: str
price: float
description: str | None = None # Optional field
def main():
print("--- Valid Item ---")
try:
item1 = Item(name="Laptop", price=1200.50)
print(item1.model_dump_json(indent=2))
except ValidationError as e:
print(e.json())
print("\n--- Invalid Item (missing price) ---")
try:
item2 = Item(name="Keyboard")
print(item2.model_dump_json(indent=2))
except ValidationError as e:
print(e.json())
if __name__ == "__main__":
main()FastAPI and Pydantic Synergy
FastAPI automatically recognizes Pydantic BaseModel objects in your endpoint function parameters. When a request comes in, FastAPI:
- Reads the JSON request body.
- Uses your Pydantic model to parse and validate the data.
- Injects the validated data as an instance of your model into your function.
It's magic!
Building a POST Endpoint
Here's how you define a POST endpoint in FastAPI that expects an Item in its request body. FastAPI handles all the parsing and validation for you!
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
description: str | None = None
tax: float | None = None
@app.post("/items/")
async def create_item(item: Item):
# The 'item' variable is now an Item object,
# already validated by Pydantic!
return {"message": "Item received successfully!", "item": item.model_dump()}
# To run this application:
# 1. Save the code as main.py
# 2. Run in terminal: uvicorn main:app --reload
# 3. Send a POST request to http://127.0.0.1:8000/items/
# with a JSON body like: {"name": "Book", "price": 29.99}Automatic Validation & Errors
If a client sends data that doesn't match your Pydantic model (e.g., missing a required field or wrong data type), FastAPI will automatically return a detailed 422 Unprocessable Entity error response.
This error message is automatically generated and very helpful for debugging both client-side and API issues.
Optional Fields & Default Values
Not all fields in your request body need to be mandatory. You can make fields optional or provide default values:
- Use
field: str | None = Nonefor optional fields that default toNone. - Use
field: int = 0to set a specific default value if the field is not provided.
This flexibility allows you to design robust and user-friendly API schemas.
Pydantic Models Check
Which of the following statements about Pydantic models in FastAPI are TRUE?
Recap: Pydantic Power
You've learned how Pydantic models are fundamental for handling request bodies in FastAPI. They provide robust data validation, automatic parsing, and clear error messages, making your API development much smoother and more reliable.
Next, we'll explore how to define explicit response models and handle HTTP status codes for various API operations!
常见问题解答
「用于请求体的 Pydantic 模型」课时是免费的吗?
是的 — 「用于请求体的 Pydantic 模型」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
「用于请求体的 Pydantic 模型」这节课中我会学到什么?
使用 Pydantic 为传入的 POST、PUT 和 DELETE 请求定义数据模式,确保可靠的数据验证。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 FastAPI Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「用于请求体的 Pydantic 模型」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 用于请求体的 Pydantic 模型
- 响应模型与状态码
- 表单数据与文件上传
- 请求头、Cookie 与自定义响应