FastAPI系列(02):第一个示例

本系列汇总,请查看这里https://www.cnblogs.com/uncleyong/p/19503695

python环境

python

pycharm

FastAPI安装

pip install fastapi

安装后就包好了pydantic、starlette

另外,FastAPI 推荐使用 uvicorn 来运行服务(Uvicorn 是基于 uvloop 和 httptools 构建的闪电般快速的 ASGI 服务器),所以还需要安装uvicorn
pip install uvicorn

示例及解释

步骤

复制代码
(1)导入FastAPI
(2)创建一个 app 实例
(3)编写一个路径操作装饰器(如 @app.get("/"))
(4)编写一个路径操作函数(如下面的 def home(): ...)
(5)定义返回值
(6)运行开发服务器(如:uvicorn main:app --reload)

示例

复制代码
from fastapi import FastAPI  # FastAPI是一个为API提供了所有功能的Python类

app = FastAPI()  # app这个实例是创建你所有API的主要交互对象。这个app也会被uvicorn所引用

@app.get("/")
def home():
    return {"msg": "welcome"}

@app.get("/shop")
def shop():
    return {"shop": "商品信息"}

启动服务:命令方式
uvicorn quickstart:app --reload

复制代码
quickstart:文件quickstart.py
app:quickstart
--reload: 热启动,代码修改后服务会自动重启,方便代码的开发

请求

启动服务:直接启动

复制代码
from fastapi import FastAPI
import uvicorn

app = FastAPI()

@app.get("/")
def home():
    return {"msg": "welcome"}

@app.get("/shop")
def shop():
    return {"shop": "商品信息"}

if __name__ == '__main__':
    uvicorn.run("quickstart:app", port=8001, reload=True)

run方法的可选参数很多,还有host等

交互式API文档

fastapi有着非常棒的交互式API文档,基于 OpenAPI 规范,能自动生产交互式API文档,支持 Swagger UI 和 ReDoc 两种交互式界面

Swagger UI

http://127.0.0.1:8001/docs

接口调试

点击"Execute"

点击"Execute"

ReDoc

http://127.0.0.1:8001/redoc

相关推荐
PieroPc1 天前
用FastAPI 和Html+css+js 写的 发票PDF文件管理系统
css·html·fastapi
钱彬 (Qian Bin)3 天前
项目实践17—全球证件智能识别系统(开发基于LabelMe标注的可视化审核接口)
qt·fastapi·全球证件识别
ghgxm5203 天前
Fastapi_00_学习策略与学习计划
python·学习·前端框架·npm·fastapi
我是菜鸟0713号4 天前
Qt + Python 算法集成的一种低耦合实践:FastAPI 服务化方案
python·qt·fastapi
a程序小傲4 天前
蚂蚁Java面试被问:向量数据库的相似度搜索和索引构建
开发语言·后端·python·架构·flask·fastapi
风送雨4 天前
FastAPI 学习教程 · 第6部分
学习·fastapi
风送雨4 天前
FastAPI 学习教程 · 第5部分
jvm·学习·fastapi
越甲八千4 天前
FastAPI传参类型
开发语言·python·fastapi