如何用FastAPI实现支持任意键值对的用户资料更新接口?
解决FastAPI接收任意键值对自定义资料的问题
你的代码无法正常工作是因为FastAPI不会自动将请求体内容解析到**kwargs中,需要显式声明请求体参数的类型。以下是两种可行的实现方式:
方法一:使用Dict类型定义请求体
直接用Dict[str, Union[str, int, float, bool]]约束键值对类型,让FastAPI正确解析请求体:
from fastapi import FastAPI, Depends from typing import Dict, Union app = FastAPI() # 抽离access_token验证逻辑(推荐,便于复用) def validate_access_token(access_token: str): # 此处添加token校验逻辑,比如验证签名、有效期等 return access_token @app.post('/update_profile') def update_profile( access_token: str = Depends(validate_access_token), profile_data: Dict[str, Union[str, int, float, bool]] ): # profile_data即为你需要的任意键值对字典 # 这里添加保存用户自定义资料的业务逻辑 return {"status": "success", "received_fields": profile_data}
方法二:使用Pydantic的Json类型
如果需要更灵活的JSON解析支持(比如后续可能扩展值的类型),可以用Pydantic的Json类型:
from fastapi import FastAPI, Depends from pydantic import Json from typing import Dict, Union app = FastAPI() def validate_access_token(access_token: str): # 同上,token校验逻辑 return access_token @app.post('/update_profile') def update_profile( access_token: str = Depends(validate_access_token), profile_data: Json[Dict[str, Union[str, int, float, bool]]] ): # 处理逻辑同上 return {"status": "success", "received_fields": profile_data}
请求示例
发送POST请求时,将自定义键值对放在JSON请求体中,access_token可通过查询参数传递:
- 请求URL:
http://localhost:8000/update_profile?access_token=your_valid_token - 请求体(JSON格式):
{ "name": "John", "nick_name": "Juju", "birth_year": 1999, "allow_newsletter": false }
若想把access_token放在请求头中(更安全),可修改参数来源:
from fastapi import Header def validate_access_token(access_token: str = Header(...)): # 验证逻辑 return access_token
此时请求时在请求头中添加access_token: your_valid_token即可。
内容的提问来源于stack exchange,提问作者Zelter Ady
相关产品推荐
相关产品推荐

