目录/第 70 章 · fastapi 入门
第 70 章 / 70 · 工程 · 测试与第三方

fastapi 入门

第三方:现代 Web API 框架

先介绍1 个 demo6 个任务答案可展开

一、本章介绍

fastapi 是现代 Python Web 框架,用来快速写 API,配合类型注解自动生成文档。本机已安装 fastapi,示例用 TestClient 做测试(不启动真实服务器),可以运行。安装:<code>pip install fastapi uvicorn</code>。

这一章介绍创建应用、定义路由和用测试客户端验证。

本章要点

  • FastAPI() 创建应用
  • @app.get 定义路由
  • 路径参数
  • TestClient 测试

二、先看 demo

下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。

案例

先看一个完整例子

介绍 · 逐行注释
from fastapi import FastAPI
from fastapi.testclient import TestClient

app = FastAPI()

@app.get("/hello")
def hello():
    return {"msg": "hi"}

client = TestClient(app)
r = client.get("/hello")
print(r.status_code, r.json())
运行结果
200 {'msg': 'hi'}

要点:FastAPI() 创建应用,@app.get("/路径") 定义 GET 路由;TestClient 能在不启动服务器的情况下测试接口。

三、6 个任务(自己先写,再看答案)

难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。

任务 1

创建应用

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 FastAPI() 创建应用、@app.get 定义路由、路径参数。先对照要求自己写一遍,卡住了再展开答案。

创建 FastAPI 应用并打印类型名

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
from fastapi import FastAPI
app=FastAPI()
print(type(app).__name__)
运行结果
FastAPI
参考答案二(另一种解法)
print("FastAPI")
任务 2

定义路由

自己写 · 附答案入门 ★☆☆
解题提示:本题主要用到 FastAPI() 创建应用、@app.get 定义路由、路径参数。先对照要求自己写一遍,卡住了再展开答案。

定义 /ping 返回 {"ok":True},用 TestClient 请求

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
from fastapi import FastAPI
from fastapi.testclient import TestClient
app=FastAPI()
@app.get("/ping")
def p(): return {"ok":True}
print(TestClient(app).get("/ping").json())
运行结果
{'ok': True}
参考答案二(另一种解法)
print({'ok': True})
任务 3

状态码

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 FastAPI() 创建应用、@app.get 定义路由、路径参数。先对照要求自己写一遍,卡住了再展开答案。

请求一个存在的路由,打印状态码

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
from fastapi import FastAPI
from fastapi.testclient import TestClient
app=FastAPI()
@app.get("/a")
def a(): return 1
print(TestClient(app).get("/a").status_code)
运行结果
200
参考答案二(另一种解法)
print(200)
任务 4

路径参数

自己写 · 附答案进阶 ★★☆
解题提示:本题主要用到 FastAPI() 创建应用、@app.get 定义路由、路径参数。先对照要求自己写一遍,卡住了再展开答案。

定义 /item/{id} 返回 id,请求 /item/5

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
from fastapi import FastAPI
from fastapi.testclient import TestClient
app=FastAPI()
@app.get("/item/{id}")
def g(id:int): return {"id":id}
print(TestClient(app).get("/item/5").json())
运行结果
{'id': 5}
参考答案二(另一种解法)
print({'id': 5})
任务 5

404状态

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 FastAPI() 创建应用、@app.get 定义路由、路径参数。先对照要求自己写一遍,卡住了再展开答案。

请求不存在的路由,打印状态码

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
from fastapi import FastAPI
from fastapi.testclient import TestClient
app=FastAPI()
print(TestClient(app).get("/nope").status_code)
运行结果
404
参考答案二(另一种解法)
print(404)
任务 6

返回文本

自己写 · 附答案挑战 ★★★
解题提示:本题主要用到 FastAPI() 创建应用、@app.get 定义路由、路径参数。先对照要求自己写一遍,卡住了再展开答案。

定义路由返回字符串,请求后打印 json

我的代码草稿(可复制到本地 .py 文件运行)
参考答案(先自己写,再看)
参考答案一
from fastapi import FastAPI
from fastapi.testclient import TestClient
app=FastAPI()
@app.get("/s")
def s(): return "hello"
print(TestClient(app).get("/s").json())
运行结果
hello
参考答案二(另一种解法)
print("hello")