# coding: utf8
from fastapi import FastAPI
from typing import Optional
app = FastAPI()
# 请求参数, 有默认值
@app.get('/read1/')
async def read1(start: int = 1, end: int = 10):
return {'start': start, 'end': end }
# 请求参数, 必填, 必须是 int 类型
@app.get('/read2/')
async def read2(start: int, end: int):
return {'start': start, 'end': end }
# 请求参数, start 有默认值, end 可选(必须是 int 类型)
@app.get('/read3/')
async def read3(start: int = 0, end: Optional[int] = None):
if end:
return {'start': start, 'end': end }
return {'start': start }
# 请求参数, start 必填, end 可选(必须是 int 类型)
@app.get('/read4/')
async def read4(start: int, end: Optional[int] = None):
if end:
return {'start': start, 'end': end }
return {'start': start }
启动: uvicorn main:app --reload
# coding: utf8
from typing import Optional
from fastapi import FastAPI, Query
app = FastAPI()
# 请求参数 q,默认是 None, 可选
@app.get('/items/')
async def items(q: Optional[str] = None):
return {"q": q}
# 设置默认值为空,如果传参,必须是字符串, 正则校验, 长度校验, (都可单独)
# 如果必须传参: None => ... 设置三个点
# max_length=5, min_length=3 => 可写成 le=5,ge=3
@app.get('/items2/')
async def items(q: Optional[str] = Query(None, max_length=5, min_length=3, regex="^1")):
return {"q": q}
# 启动: uvicorn main:app --reload
# coding: utf8
from typing import Optional, List
from fastapi import FastAPI,Query
app = FastAPI()
@app.get('/items/')
async def items(q: Optional[List[str]] = Query(None)):
data = {}
if q:
data.update({'q': q})
return dat
http://10.11.9.247:8000/items/?q=a&q=b&q=c
{"q":["a","b","c"]}