SpringBoot的请求参数的接受的方式和FastAPI的请求参数接受接受参数的区别

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 会按照以下优先级自动解析参数:

  1. 路径参数(如 /items/{item_id}
  2. 查询参数(如 ?name=John
  3. 请求体(JSON 或表单数据)

总结

查询参数:直接声明为函数参数,或通过 request.query_params 获取。
路径参数:在路径中声明(如 /{id}),并在函数参数中定义。
JSON 请求体:使用 Pydantic 模型(如 item: Item)。
表单数据:使用 Form(...)
文件上传:使用 File(...)UploadFile
原始请求数据:通过 Request 对象直接访问。

FastAPI 的语法更简洁且类型安全,结合 Pydantic 模型可以高效处理复杂请求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

堕落年代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值