# -*- coding: UTF-8 -*-
from fastapi import FastAPI
app = FastAPI()
@app.get("/test/xx")
async def read_item_me():
return {"me": 'me'}
@app.get("/test/{item_id}")
async def read_item(item_id: str):
return {"item_id": item_id}
@app.get("/")
async def main():
return {"message": "Hello,FastAPI"}
if __name__ == '__main__':
import uvicorn
uvicorn.run(app='params1:app', host="127.0.0.1", port=8000, reload=True, debug=True)
一、几种参数请求类型
1.无参get请求
@app.get("/")
async def main():
return {"message": "Hello,FastAPI"}
@app.get("/")就是路由路径配置,目录为根目录,方法为get,调用函数为main。
与上面类似的
@app.get("/test/xx")
async def read_item_me():
return {"me": 'me'}
该路由路径为/test/xx,方法get,返回一个json。
2.路径参数
@app.get("/test/{item_id}")
async def read_item(item_id: str):
return {"item_id": item_id}
该路由有路径参数item_id,同时函数参数中也声明item_id,并且指定他的参数类型为str。
参数类型限制,如果我把
@app.get("/test/{item_id}")
async def read_item(item_id: str):
return {"item_id": item_id}
改为
@app.get("/test/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
则参数就只能是数字不能是其他类型
如果输入string,float等非int类型会报错提示
3.查询参数
# -*- coding: UTF-8 -*-
from fastapi import FastAPI
import uvicorn
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
if __name__ == '__main__':
uvicorn.run(app='params1:app', host="127.0.0.1", port=8000, reload=True, debug=True)
http://127.0.0.1:8000/items/?skip=0&limit=2
其中?后面的skip=0&limit=2就是查询参数
4.多路径和查询参数
# -*- coding: UTF-8 -*-
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(
user_id: int, item_id: str, q: str = None, short: bool = False
):
item = {"item_id": item_id, "owner_id": user_id}
if q:
item.update({"q": q})
if not short:
item.update(
{"description": "This is an amazing item that has a long description"}
)
return item
if __name__ == '__main__':
uvicorn.run(app='params1:app', host="127.0.0.1", port=8000, reload=True, debug=True)
async def read_user_item(
user_id: int, item_id: str, q: str = None, short: bool = False
):
函数的参数user_id和item_id是路径参数,是必须的。
q:str=None 意思是非必需的。
如果没有q,short为ture那么只返回user_id和item_id
问号?之后多个查询参数之间用&连接
二、路径参数和查询参数的选项
1.必选和非必选参数
参数的可选和必选主要是通过是否给默认值来决定的:
@app.get("/items/{item_id}")
async def read_user_item(item_id: str):
item = {"item_id": item_id}
return item
@app.get("/items/{item_id}")
async def read_user_item(item_id: str, needy: str):
item = {"item_id": item_id, "needy": needy}
return item
上述的代码中 needy 没有给与默认的值,当个没提交这个值的时候,会提示错误:
再例如
@app.get("/required/")
async def i(A: str, B: str = 'Hello..', C: str = 'He..'):
return {'required': A+B+C}
A没有默认值,B,C有默认值,所以A是必须有的,BC可以没有
2.限制参数的类型
上面也说道过,在函数参数后面声明参数的类型,可以指定参数类型
3.限制参数的长度
# -*- coding: UTF-8 -*-
from fastapi import FastAPI, Query
import uvicorn
app = FastAPI()
@app.get("/items/")
async def read_items(q: str = Query(..., min_length=3, max_length=5)):
#填None就是默认值 填 ...则是必填项
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
results.update({"q": q})
return results
if __name__ == '__main__':
uvicorn.run(app='params1:app', host="127.0.0.1", port=8000, reload=True, debug=True)
q为查询路径,填None就是默认值 填 ...则是必填项,min_length,max_length规定长度,如果超出长度范围就会报错
4.正则表达式
@app.get("/items/")
async def read_items(q: str = Query(None, min_length=3, max_length=50, regex="^fast")):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
参数q只允许开头是fast才行
当然因为q参数为None非必须,不传他也行
4,参数是列表
#列表
@app.get("/items/")
async def read_items3(q: List[str] = Query(["foo", "bar"])):
query_items = {"q": q}
return query_items
5.弃用参数
#弃用参数
@app.get("/items5/")
async def read_items5(
q: str = Query(
None,
description="Query",
min_length=3,
max_length=50,
regex="^fast",
deprecated=True,
)
):
results = {"items": [{"item_id": "Foo"}, {"item_id": "Bar"}]}
if q:
results.update({"q": q})
return results
deprecated=True,该参数无法使用
三,路径参数的枚举
# -*- coding: UTF-8 -*-
from fastapi import FastAPI, Query
from typing import List
from enum import Enum
import uvicorn
app = FastAPI()
class Language(str, Enum):
go = 'Golang'
py = 'Python'
cpp = 'C++'
ts = 'Typescript'
app = FastAPI()
@app.get("/{language}")
async def get_day(language: Language):
if language == Language.go:
return {"language": language, "message": "gogogogogo,"}
if language.value == 'Python':
return {"language": language, "message": "pypypypy"}
if language.value == 'Typescript':
return {"language": language, "message": "tststststs"}
if language.value == 'C++':
return {"language": language, "message": "C++C++C++"}
return {"message": "error"}
if __name__ == '__main__':
uvicorn.run(app='params1:app', host="127.0.0.1", port=8000, reload=True, debug=True)