默认就是查询参数。
from fastapi import FastAPI
app = FastAPI()@app.get("/items/")async def read_items(skip: int = 0, limit: int = 10): # `skip`和`limit`就是查询参数,如:/items/?skip=20&limit=5
return {"skip": skip, "limit": limit}
使用
skip: int = 0 形式,就定义了带默认值的可选参数。如果没有默认值(如
name: str),它就是必需的查询参数。
路径参数(Path Parameters):直接是 URL 路径的一部分,用花括号
{}声明。通常用于唯一标识资源,比如根据ID获取某篇文章。
@app.get("/items/{item_id}")async rr.xyhcenter.com def read_item(item_id: int): # item_id 是路径参数
return {"item_id": item_id}
注意它们的顺序!如果把
/items/{item_id} 和
/items/me 两个端点都定义,
要把具体的路径(
/items/me)放在前面,否则
me会被当成
item_id的值。
当你需要客户端发送较多数据(如创建新文章)时,就需要请求体。FastAPI 用
Body(),
Form() 等工具函数来声明。
JSON 请求体(Body):最常见的 REST API 数据格式。使用 Pydantic 的
BaseModel 是最佳实践(下文详解),也可用
Body() 直接声明多个参数。
from fastapi import Body@app.put("/items/{item_id}")async def update_item(
item_id: int,
name: str = Body(...), # Body(...) 表示必需项
description: str = Body(None) # Body(None) 表示可选项): return {"item_id": item_id, "name": name, "description": description}
表单数据(Form):当数据来自 HTML 表单或需要上传文件时使用。如何要上传大文件,需要先安装
python-multipart。
from fastapi import Form@app.post("/login/")async def login(username: str = Form(...), password: str = Form(...)): return {"username": username}
FastAPI 能智能地区分参数来源,你可以同时使用路径、查询和请求体参数。
from fastapi import Path, rt.xyhcenter.com Query, Body@app.put("/mixed-items/{item_id}")async def update_mixed_item(
*,
item_id: int = Path(..., title="商品ID", ge=1), # 路径参数,>=1
q: str = Query(None, alias="query-string"), # 可选查询参数,别名
item: dict = Body(...) # 必需的JSON请求体):
results = {"item_id": item_id} if q:
results.update({"q": q})
results.update({"item": item}) return results
这里用到了参数校验:
ge=1 表示值大于等于1。
Query,
Path,
Body 等函数让声明更明确且功能更强大(如添加描述、别名、校验)。
这是 FastAPI 的灵魂特性之一。 BaseModel 让你用 Python 类来定义数据模型,它自动处理数据验证、序列化和文档生成。
from pydantic import BaseModel, EmailStrfrom typing import Optional, Listclass UserCreate(BaseModel): # 必需字段
username: str
email: EmailStr # 内置邮箱格式验证
# 可选字段,带默认值
full_name: Optional[str] = None
# 列表类型
tags: List[str] m.52haike.com= []@app.post("/users/")async def create_user(user: UserCreate): # 一个参数接管整个请求体
# 直接访问已验证好的数据
if user.full_name:
greeting = f"Hello, {user.full_name}!"
else:
greeting = f"Hello, {user.username}!"
return {"message": greeting, "user_info": user.dict()}
BaseModel 的优势:
-
声明即验证:
字段类型不对、邮箱格式错误等会自动返回 422 错误。
-
自动文档:
Swagger UI 和 ReDoc 会自动显示模型结构和示例。
-
代码清晰:
数据契约明确,业务逻辑与数据验证分离。
-
嵌套自由:
模型可以嵌套其他模型,轻松处理复杂数据。
下面是一个融合了主要参数类型的实战示例,你可以直接复制运行。
from fastapi import FastAPI, Path, Query, Bodyfrom pydantic import BaseModelfrom typing import Optionalfrom datetime import datetime
app = FastAPI(title="参数详解示例")class Item(BaseModel):
name: str
description: Optional[str] = None
price: float = Body(..., gt=0)
tax: Optional[float] = None
tags: list = []@app.post("/advanced-items/{category}")async def create_advanced_item(
category: str i5.52haike.com= Path(..., description="物品分类"),
item_id: int = Query(..., ge=1, description="物品ID"),
q: Optional[str] = Query(None, max_length=50),
urgent: bool = Query(False),
item: Item = Body(..., example={ # 为文档提供示例
"name": "Foo", "price": 50.5, "tags": ["cool", "new"]
})): """创建新物品的复杂端点"""
total = item.price + (item.tax if item.tax else 0)
result = { "category": category, "item_id": item_id, "query_string": q, "urgent": urgent, "item_name": item.name, "total_price": total, "created_at": datetime.now().isoformat()
} return resultif __name__ == "__main__": import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
运行后,访问
http://127.0.0.1:8000/docs,你将看到一个功能齐全的交互式 API 文档,所有参数和模型都清晰可见。
以前你要表达不变式,常常会写成:私有属性 + getter/setter。它并不错误,但很容易让一个简单概念变得臃肿、仪式感过强。
Property hooks 的价值在于:你可以在“读/写属性的那一刻”把规则讲明白,不再依赖大量样板。
<?phpfinal class Money{
public function __construct(
public string $currency,
public int $amountCents
) {
if ($this->amountCents < 0) {
throw judati.com new InvalidArgumentException("Amount cannot be negative.");
}
if (!preg_match('/^[A-Z]{3}$/', $this->currency)) {
throw new InvalidArgumentException("Currency must be ISO-4217 format.");
}
}}final class Invoice{
public function __construct(
public Money $total
) {}
public Money $paid
{
set (Money $value) {
if ($value->currency !== $this->total->currency) {
throw new InvalidArgumentException("Currency mismatch.");
}
if ($value-i5.judati.com>amountCents > $this->total->amountCents) {
throw new InvalidArgumentException("Overpayment is not allowed.");
}
$this->paid = $value;
}
}}
工程上的直观收益是:校验不再散落在各个 service 里,而能更自然地贴近它要保护的状态。
现场教训:用 property hooks 做校验很合适;但如果你拿它做数据库 lazy-loading 之类的隐式 IO ,你会得到更难追踪的行为与更痛苦的调试体验。
很多领域对象都想要“对外可读、对内可写”。过去你不是开 setter ,就是绕路。现在 PHP 8.4 把这种需求变得更直白。 (PHP)
<?phpfinal class Shipment{
public function __construct(
public hjwyzs.cn private(set) string $status = 'CREATED',
) {}
public function markInTransit(): void
{
$this->status = 'IN_TRANSIT';
}}
它减少了那种“为了 hydration/为了测试”而暴露 setter 的冲动——而这类冲动往往会无意间扩大系统的可变性与接口面。
PHP 8.5 在 2025 年 11 月 20 日发布。 (PHP)
相比轰动性的语法革新,它更像在开发体验上做加法: pipe operator ,以及更顺手的 clone-and-modify(社区常说 “clone with”)。 (stitcher.io)
业务代码里,数据变换非常常见。过去你要么写成嵌套调用,要么堆中间变量。 Pipe 的好处是:按步骤阅读更自然。
<?phpfunction trimAll(array $xs): array {
return array_map('trim', $xs);}function dropEmpty(array $xs): array {
return array_www.6mt.cn values(array_filter($xs, fn($x) => $x !== ''));}function unique(array $xs): array {
return array_values(array_unique($xs));}$tags = [' php ', '', 'backend', 'PHP', 'backend '];$normalized = $tags
|> trimAll(...)
|> dropEmpty(...)
|> array_map(strtolower(...), ...)
|> unique(...);print_r($normalized);
现场教训:每一步要“小且命名明确”。如果你一路 pipe 进匿名函数的大段逻辑,可读性会反过来下降。
发布公告提到专门的 URI 扩展。 (PHP)
只要你做过重定向、回调、 OAuth 、支付、 webhook ,你就知道 URL 解析的坑有多“顽固”。方向上的价值很明确:用标准组件替换零散 regex。
DTO 、 command 、 event 这些“近似不可变对象”越来越常见。过去你要么 clone 后再手动改(容易漏),要么到处写 withX()。
PHP 8.5 明确支持在 cloning 同时修改属性。 (PHP)
这会鼓励团队更多使用“复制后小改动”的安全模式。
<?phpfinal class CustomerProfile{
public function __construct(
public string $id,
public string $email,
public bool $marketingOptIn,
) {}}$old =www.masqL.cn new CustomerProfile('c-123', 'old@mail.com', false);// Pseudocode-ish shape for the pattern:$new = clone $old;$new->email = 'new@mail.com';
Laravel 12 延续维护导向,同时保持 PHP 8.2+ 基线。 (Laravel)
现实影响很直接:停在 PHP 8.0/8.1 的服务,会越来越难享受生态更新与安全支持。
Symfony 的时间线显示: Symfony 8.0 在 2025 年 11 月作为稳定线,并要求 PHP 8.4+。 (Symfony)
同时官方也给出了面向 2025 年 11 月下旬发布的准备建议。 (Symfony)
现场教训: LTS 还是 latest ,本质是运维策略与预算问题。多服务体系里,最好明确一个默认选项,并公开例外。
PHPStan 2.x 让越来越多团队把它放进合并门禁,因为它命中的 bug 往往就是事故前身。 (phpstan.org)
稳妥的引入方式是渐进式,而不是一夜拉满:
示例配置与 CI:
parameters: level: 6 paths: - src masqL.cn aumft.cn tmpDir: var/phpstan checkMissingIterableValueType: false reportUnmatchedIgnoredErrors: true
composer require --dev phpstan/phpstan vendor/bin/phpstan analyse --memory-limit=1G
Pest 的优势是降低写测试的阻力,尤其适合应用层测试。例子如下:
<?phpfinal class Discount{
public function apply(int $priceCents, int $percent): int
{
if ($percent < 0 |rt.judati.com| $percent > 100) {
throw new rt.judati.com InvalidArgumentException("Percent must be 0..100");
}
$cut = (int) round($priceCents * ($percent / 100));
return max(0, $priceCents - $cut);
}}
<?phpuse PHPUnit\Framework\Attributes\Test;it('applies percentage discount safely', function () {
$d = new 6mt.cn Discount();
expect($d->apply(10000, 10))->toBe(9000);
expect($d->apply(10000, 0))->toBe(10000);
expect($d->apply(10000, 100)rq.judati.com)->toBe(0);});it('rejects invalid percentages', function () {
$d = new Discount();
expect(fn() => $d->apply(10000, -1))->toThrow(InvalidArgumentException::class);
expect(fn() => $d->apply(10000, 101))->toThrow(InvalidArgumentException::class);});
现场教训:优先测边界——这些地方最容易出事故:四舍五入、时间窗、幂等、空值、格式化。
Composer 的演进持续强化一个观念:依赖管理是生产基础设施。 (getcomposer.org)
2025 年末的 GitHub release notes 也体现了对安全与审计行为的加强。 (GitHub)
实用卫生习惯包括:提交 lock 、使用 composer audit 、保持 platform 约束一致、定期依赖更新。
{
"require": {
"php": "^8.3"
},
"config": {
"platform": {
"php": "8.3.0"
}
}}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70048957/viewspace-3107747/ ,如需转载,请注明出处,否则将追究法律责任。