url与交互式文档
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/me/xx")
async def index():
return {"me": "me"}
@app.get("/me/{item_id}")
async def index_item(item_id: str):
return {"me": item_id}
@app.get("/")
async def index_none():
return "hello world"
if __name__ == "__main__":
uvicorn.run(app, host="127.0.0.1", port=8001)
进阶的url-枚举
from fastapi import FastAPI
from enum import Enum
import uvicorn
app = FastAPI()
class Name(str, Enum):
bruce = 'bruce'
amy = 'amy'
customer = 'customer'
@app.get('/{who}')
async def index(who: Name):
if who == Name.bruce:
return {'bruce': who, 'message': 'bruce is No.1'}
if who.value == 'amy':
return {'amy': who, 'message': 'amy is No.2'}
else:
return {'customer': who, 'message': 'customer is No.3'}
@app.get("/")
async def index_demo():
return 'hello world'
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
查询参数
from fastapi import FastAPI
import uvicorn
app = FastAPI()
fake = [{'bar': 'bar'}, {'foo': 'foo'}, {'java': 'java'}]
# http://127.0.0.1:8001/items/?skip=0&limit=1
# return [{'bar': 'bar'}]
@app.get('/items/')
async def index(skip: int = 0, limit: int = 10):
return fake[skip: limit]
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
查询参数
from fastapi import FastAPI
import uvicorn
app = FastAPI()
fake = [{'bar': 'bar'}, {'foo': 'foo'}, {'java': 'java'}]
# http://127.0.0.1:8001/items/?skip=0&limit=1
# return [{'bar': 'bar'}]
@app.get('/items/')
async def index(skip: int = 0, limit: int = 10):
return fake[skip: limit]
# http://127.0.0.1:8001/add/?a=100
# return 200
@app.get('/add/')
async def add(a: int = 10, b: int = 100):
return a + b
@app.get('/user/{user_id}/item/{item_id}')
async def user(
user_id: int, item_id: str, q: str = None, short: bool = False
):
item = {'item_id': item_id, 'user_id': user_id}
if q:
item.update({'q': q})
if not short:
item.update({'description': 'Bruce you are handsome'})
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
请求体(post/put)
from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
description: str = None
tax: float
@app.post("/items/")
async def index(item: Item):
print(item.dict())
return item, "人生没有意义"
@app.put("/items/{item_id}")
async def show(item_id: int, item: Item = None, q: str = None):
result = {'item_id': item_id, 'item': item}
if q:
result.update({'q': q})
return result
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
查询参数&字符串验证
from fastapi import FastAPI, Query
import uvicorn
from pydantic import BaseModel
from typing import List
app = FastAPI()
class Item(BaseModel):
name: str
age: int = None
# 限制长度
@app.get('/item/')
async def index(q: str = Query(None, min_length=3, max_length=20)):
# None是默认参数,...是必传参数
result = {"bruce": 'university'}
if q:
result.update({'q': q})
return result
# 正则表达式
@app.get("/item1/")
async def index1(q: str = Query(None, min_length=3, max_length=20, regex="^nice")):
result = {'bruce': 'university', 'apple': 'pee'}
if q:
result.update({'q': q})
return result
# 列表
@app.get("/item2/")
async def index2(q: List[str] = Query(['jia', 'bruce'])):
result = {'q': q}
return result
# 别名
# http://127.0.0.1:8001/item3/?item-query=xxxx
@app.get("/item3/")
async def index3(q: str = Query(None, alias='item-query')):
result = {'bruce': 'university'}
if q:
result.update({'q': q})
return result
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
路径参数&字符串验证
from fastapi import FastAPI, Path, Query
import uvicorn
app = FastAPI()
@app.get("/item/{item_id}")
async def index(item_id: int = Path(..., ge=3, le=10),
q: str = Query(None, min_length=3, max_length=10)):
# int 对应的是ge和le
# str 对应的是min_length 和 max_length
result = {'item_id': item_id}
if q:
result.update({'q': q})
return result
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
混合参数, request_body
from fastapi import FastAPI, Path, Query
import uvicorn
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
age: int
# 混合传参
@app.put("/item/{item_id}")
async def index(
item_id: int = Path(..., ge=3, le=10),
q: str = Query(None, min_length=3, max_length=10),
item: Item = None
):
result = {'item_id': item_id}
if q:
result.update({'q': q})
if item:
result.update({'item': item})
return result
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
请求体验证
from fastapi import FastAPI, Path, Query
import uvicorn
from pydantic import BaseModel, Field
app = FastAPI()
class Item(BaseModel):
name: str = None
age: int = Field(..., gt=0)
@app.post("/item/{item_id}")
async def index(
item_id: int = Path(..., ge=3, le=10),
q: str = Query(None, min_length=3, max_length=10),
item: Item = None
):
result = {'item_id': item_id}
if q:
result.update({'q': q})
if item:
result.update({'item': item})
return result
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
请求体套请求体
{
"item_id": "bruce",
"q": "qqq",
"item": {
"name": "string",
"age": 0,
"tags": [
"string"
],
"images": [
{
"url": "java",
"name": "www.java.com"
}
]
}
}
可以构造一个模型类中嵌套模型类的文件格式
from fastapi import FastAPI, Path, Query
import uvicorn
from typing import List, Set
from pydantic import BaseModel, Field
app = FastAPI()
class Image(BaseModel):
url: str = None
name: str = None
class Item(BaseModel):
name: str = None
age: int = Field(..., ge=0)
tags: Set[str] = set()
images: List[Image] = None
@app.post("/item/{item_id}")
async def index(
item_id: str = Path(..., min_length=3),
q: str = Query(None, min_length=3),
item: Item = None
):
result = {"item_id": item_id}
if q:
result.update({'q': q})
if item:
result.update({'item': item})
return result
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
额外参数
from fastapi import FastAPI
import uvicorn
from pydantic import BaseModel
from uuid import UUID, uuid1
from datetime import time
class Item(BaseModel):
start_time: time
end_time: time
process_time: time
app = FastAPI()
@app.post("/item/{item_id}/")
async def index(item_id: UUID,
item: Item = None):
result = {"item_id": item_id}
if item:
result.update(item)
return result
if __name__ == '__main__':
print('uuid:', uuid1())
uvicorn.run(app, host="127.0.0.1", port=8001)
postman测试cookie
from fastapi import FastAPI, Cookie
import uvicorn
app = FastAPI()
@app.get("/item/")
async def index(*, item_id: str = Cookie(None)):
return {"item_id": item_id}
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1", port=8001)
postman测试