[toc]
FastAPI实验
1 实验类型
验证型,2学时,必选实验
2 实验目的
掌握FastAPI不同类型请求参数的实现方法;
3 实验内容与要求
以不同的方式向FastAPI传递参数。
4 实验环境
Microsoft Edge/Chrome/Firefox
等浏览器,Visual Studio Code
,REST Client
,Python 3.4+
,FastAPI
,Uvicorn
5 步骤
安装依赖
- 创建工作目录
学号
,最终目录结构如下(包含创建的各类文件):
学号:.
│ form_test.http
│ form_test.py
│ get_test.http
│ get_test.py
│ jinja2_test.http
│ jinja2_test.py
│ json_test.http
│ json_test.py
│ path_test.http
│ path_test.py
│ query_test.http
│ query_test.py
│ requirements.txt
├─static
│ styles.css
└─templates
item.html
注:后续代码均在工作目录创建
- 创建虚拟环境
.venv
- 激活虚拟环境:
- 安装依赖包:
pip install fastapi
pip install "uvicorn[standard]"
pip install python-multipart
pip install jinja2
pip list
py -m pip freeze > requirements.txt
最简单的API
使用GET方式定义路径/
处理程序,返回简单的JSON消息
-
在工作目录新建
{WORK_DIR}\get_test.py
-
编写get类型的API,如:
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
'''启动FastAPI服务器'''
config = uvicorn.Config(app = app, port = 8888, log_level = "info", reload = False)
server = uvicorn.Server(config)
server.run()
- 启动服务器
注:后续实验启动方式类似不再赘述
- 编写REST Client测试代码并测试发送请求,如:
- 在浏览器中访问
http://127.0.0.1:8888/doc
,观察关于API的文档
路径参数
在URL路径中使用与Python格式化字符串中占位符类似的语法挂载参数,如/items/{item_id}
,其中item_id为占位符
- 创建文件
path_test.py
,使用路径参数传递数据
from fastapi import FastAPI
import uvicorn
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
if __name__ == "__main__":
'''启动FastAPI服务器'''
config = uvicorn.Config(app = app, port = 8888, log_level = "info", reload = False)
server = uvicorn.Server(config)
server.run()
- 编写REST Client测试代码并测试发送请求,如:
@host = http://127.0.0.1:8888
### 测试正确参数123
GET {{host}}/items/123 HTTP/1.1
### 测试错误参数
GET {{host}}/items/abc HTTP/1.1
查询参数
以GET方式直接在URL地址后挂载查询参数,如/items/?skip=0&limit=10
,skip与limit为查询参数
- 创建文件
query_test.py
,使用路径参数传递数据
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__":
'''启动FastAPI服务器'''
config = uvicorn.Config(app = app, port = 8888, log_level = "info", reload = False)
server = uvicorn.Server(config)
server.run()
- 编写REST Client测试代码并测试发送请求,如:
请求体
以POST方式传递JSON数据
- 创建文件
json_test.py
,使用请求体参数传递数据
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
class Item(BaseModel):
'''参数类型'''
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
app = FastAPI()
@app.post("/items/")
async def create_item(item: Item):
return item
if __name__ == "__main__":
'''启动FastAPI服务器'''
config = uvicorn.Config(app = app, port = 8888, log_level = "info", reload = False)
server = uvicorn.Server(config)
server.run()
- 编写REST Client测试代码并测试发送请求,如:
@host = http://127.0.0.1:8888
POST {{host}}/items HTTP/1.1
content-type: application/json
{
"name": "Foo",
"description": "An optional description",
"price": 45.2,
"tax": 3.5
}
表单
以POST方式向服务提交表达数据
- 创建文件
form_test.py
,使用表单传递数据
from fastapi import FastAPI, Form
import uvicorn
app = FastAPI()
@app.post("/login/")
async def login(username: str = Form(), password: str = Form()):
return {"username": username}
if __name__ == "__main__":
'''启动FastAPI服务器'''
config = uvicorn.Config(app = app, port = 8888, log_level = "info", reload = False)
server = uvicorn.Server(config)
server.run()
- 编写REST Client测试代码并测试发送请求,如:
@host = http://127.0.0.1:8888
POST {{host}}/login HTTP/1.1
content-type: application/x-www-form-urlencoded
username=andy&password=123456
自定义响应(Jinja2)
FastAPI默认返回JSON数据即JSONResponse,同时也支持多种不同形式响应类型,其中包括使用Jinja2
模板返回Html代码
补充:FastAPI可用的响应,Response,HTMLResponse,PlainTextResponse,JSONResponse(默认),ORJSONResponse,UJSONResponse,RedirectResponse,StreamingResponse,FileResponse
- 创建文件
jinja2_test.py
,使用jinja2返回html
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import uvicorn
app = FastAPI()
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
@app.get("/items/{id}", response_class=HTMLResponse)
async def read_item(request: Request, id: str):
return templates.TemplateResponse("item.html", {"request": request, "id": id})
if __name__ == "__main__":
'''启动FastAPI服务器'''
config = uvicorn.Config(app = app, port = 8888, log_level = "info", reload = False)
server = uvicorn.Server(config)
server.run()
- 创建
templates/item.html
用于将id显示至客户端
<html>
<head>
<title>Item Details</title>
<link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
</head>
<body>
<h1>Item ID: {{ id }}</h1>
</body>
</html>
- 创建
static/style.css
用于修饰item.html
- 编写REST Client测试代码并测试发送请求,如: