1. 获取所有查询参数(类似 Spring Boot 的 @RequestParam Map
)
在 Spring Boot 中,你可能这样获取所有查询参数:
@GetMapping("/search")
public Map<String, String> search(@RequestParam Map<String, String> params) {
return params;
}
FastAPI 对应实现:
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/search")
async def search(request: Request):
# 获取所有查询参数(字典形式)
query_params = dict(request.query_params)
return query_params
访问 /search?name=John&age=30
会返回:
{"name": "John", "age": "30"}
2. 获取路径参数(类似 Spring Boot 的 @PathVariable
)
Spring Boot 示例:
@GetMapping("/user/{id}")
public String getUser(@PathVariable String id) {
return "User ID: " + id;
}
FastAPI 对应实现:
@app.get("/user/{id}")
async def get_user(id: str):
return {"user_id": id}
3. 获取请求体(JSON,类似 Spring Boot 的 @RequestBody
)
Spring Boot 示例:
@PostMapping("/user")
public User createUser(@RequestBody User user) {
return user;
}
FastAPI 对应实现:
from pydantic import BaseModel
class User(BaseModel):
name: str
age: int
@app.post("/user")
async def create_user(user: User):
return user
访问时发送 JSON 数据:
{"name": "John", "age": 30}
4. 获取表单数据(类似 Spring Boot 的 @RequestParam
)
Spring Boot 示例:
@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password) {
return "Login success";
}
FastAPI 对应实现:
from fastapi import Form
@app.post("/login")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
5. 获取所有参数(查询参数 + 路径参数 + 请求体)
如果需要同时获取多种参数,可以组合使用:
from fastapi import Request, Body
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/{item_id}")
async def create_item(
item_id: int, # 路径参数
request: Request, # 原始请求对象
item: Item, # JSON 请求体
q: str = None # 查询参数
):
# 获取所有查询参数
query_params = dict(request.query_params)
return {
"item_id": item_id,
"query_params": query_params,
"item": item.dict(),
"q": q
}
6. 动态获取原始请求数据(类似 Spring Boot 的 HttpServletRequest
)
如果需要直接处理原始请求数据(如非结构化数据):
from fastapi import Request
@app.post("/raw")
async def raw_request(request: Request):
# 获取原始请求体(bytes)
raw_body = await request.body()
# 获取请求头
headers = dict(request.headers)
return {
"body": raw_body.decode(),
"headers": headers
}
7. 获取文件上传(类似 Spring Boot 的 @RequestParam("file") MultipartFile
)
from fastapi import UploadFile, File
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
return {
"filename": file.filename,
"content_type": file.content_type
}
参数优先级和自动解析
FastAPI 会按照以下优先级自动解析参数:
- 路径参数(如
/items/{item_id}
) - 查询参数(如
?name=John
) - 请求体(JSON 或表单数据)
总结
• 查询参数:直接声明为函数参数,或通过 request.query_params
获取。
• 路径参数:在路径中声明(如 /{id}
),并在函数参数中定义。
• JSON 请求体:使用 Pydantic 模型(如 item: Item
)。
• 表单数据:使用 Form(...)
。
• 文件上传:使用 File(...)
和 UploadFile
。
• 原始请求数据:通过 Request
对象直接访问。
FastAPI 的语法更简洁且类型安全,结合 Pydantic 模型可以高效处理复杂请求。