1、路径参数
@app.get("/getfilecontent/{id}/{pre}")
def get_filecontent(id,pre):
"""
路径参数,测试接口,读取当前工作目录下的file.txt文件,返回txt中的内容
:param id: The ID of the item to retrieve.
:param pre: An optional query parameter.
"""
with open('file.txt', 'r') as f:
content = f.read()
logger.info("start2")
return {"Hello": content}
限制允许的值
例1:
class UserType(str,Enum):
STANDARD="standard"
ADMIN="admin"
例2:
async def get_user(type:UserType,id:int)
ge 大于或等于
2、查询参数
@app.get("/users")
def get_users(page:int=1,size:int=10):
"""
查询参数,测试接口
:param page: The ID of the item to retrieve.
:param size: An optional query parameter.
"""
return {"Hello": size}
3、主体数据
例1:
from fastapi import Body
@app.post("/userstest")
async def create_usertest(name:str=Body(...),age:int=Body(...)):
return{"name":name,"age":age}
用postman测试,如下:
例2:
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
@app.post("/itemes/")
async def create_iteem(item: Item):
"""主体数据 测试 原始的(raw) body中负载json 但是使用了pydantic,避免了上述冗长"""
return item
4、表单数据和文件上传
(1)表单数据
from fastapi import Form
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
"""表单数据 测试"""
return {"username": username}
(2)文件上传
pip install python-multipart。
from fastapi import FastAPI, File,UploadFile,Response
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
logger.info("start")
try:
with open(file.filename, "wb") as local_file:
local_file.write(file.file.read())
return JSONResponse(content={"message": "File uploaded and saved successfully 上传成功,定位成功"})
except Exception as e:
logger.info(str(e))
return JSONResponse(content={"message": f"An error occurred: {str(e)}"}, status_code=500)
return {"filename": file.filename}