路径参数与查询参数
理解如何使用路径参数从 URL 中获取动态数据,以及如何处理可选的查询参数。
路径参数与查询参数 是 CoddyKit 上的免费 FastAPI Backend Development Bootcamp 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 FastAPI Backend Development Bootcamp 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Dynamic URLs for APIs
APIs often carry data right in the URL — fetching a product by ID or filtering a list. FastAPI gives you clean ways to capture that. Let's dig in.
Meet Path Parameters
Path parameters are URL segments that pin down a specific resource, written in curly braces like /items/{item_id}. Perfect for one exact item.
Your First Path Parameter
Match a path segment to a function arg by name: /items/{item_id} maps to item_id. The type hint int auto-converts it.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id, "message": "Here is your item!"}Power of Type Hints
Type hints like item_id: int drive validation. Hit /items/abc and FastAPI returns a clean error automatically. Use str, int, float, bool, UUID.
Handling Multiple Paths
You can take several path parameters in one route. FastAPI matches them by name, so the order in your function signature doesn't matter.
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(user_id: int, item_id: str):
return {"user_id": user_id, "item_id": item_id}What are Query Parameters?
Query parameters are key-value pairs after a ?, like /items?skip=0&limit=10. They are optional — ideal for filtering, paging, or sorting.
Your First Query Parameter
Any function arg that is not in the path becomes a query parameter automatically. Here, skip and limit are typed integers.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}Optional Queries & Defaults
Make a query parameter optional by giving it a default. For a None default, type it as Optional[str] so FastAPI knows it may be missing.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/products/")
async def read_products(q: Optional[str] = None, page_size: int = 20):
results = {"page_size": page_size}
if q:
results.update({"search_query": q})
return resultsPath + Query Power
Combine both: path parameters are required, query parameters stay optional with defaults. FastAPI sorts out which is which seamlessly.
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/orders/")
async def get_user_orders(user_id: int, status: Optional[str] = None, limit: int = 10):
return {"user_id": user_id, "status": status, "limit": limit, "message": "User orders fetched."}Quick Check on Parameters
Consider the following FastAPI endpoint:
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get("/books/{book_id}")
async def get_book(book_id: int, author: str = "Unknown", published_year: Optional[int] = None):
return {
"book_id": book_id,
"author": author,
"published_year": published_year
}Which of the following URLs would successfully call this endpoint and return a published_year?
Recap: Dynamic API Routes
Great work! You made routes dynamic with path parameters for required IDs, query parameters for optional filters, and type hints for free validation.
常见问题解答
「路径参数与查询参数」课时是免费的吗?
是的 — 「路径参数与查询参数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 FastAPI Backend Development Bootcamp 课程的其余内容,请升级到 CoddyKit PRO。 FastAPI Backend Development Bootcamp 课程共包含 4 节课。
「路径参数与查询参数」这节课中我会学到什么?
理解如何使用路径参数从 URL 中获取动态数据,以及如何处理可选的查询参数。 你通过在浏览器中直接运行的动手代码来练习 FastAPI Backend Development Bootcamp,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 FastAPI Backend Development Bootcamp 需要有经验吗?
无需任何先前经验。CoddyKit 上的 FastAPI Backend Development Bootcamp 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「路径参数与查询参数」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 FastAPI Backend Development Bootcamp 课中编写并运行代码吗?
能。每节 FastAPI Backend Development Bootcamp 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。