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

相关推荐
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
CaffeinePro4 天前
依赖注入:FastAPI最核心的解耦能力案例解析
后端·fastapi
曲幽8 天前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
CaffeinePro11 天前
Pydantic深度使用:数据校验、枚举、ORM映射
后端·fastapi
jay神14 天前
基于 FastAPI + Vue 的宠物领养管理系统
前端·vue.js·python·毕业设计·fastapi·宠物
染指111014 天前
6.AI大模型-搭建本地大模型服务体系
fastapi·oneapi
codeaideaai16 天前
使用UV创建python项目
python·fastapi·uv
放下华子我只抽RuiKe516 天前
FastAPI 全栈后端(八):部署与运维
运维·数据库·react.js·oracle·数据挖掘·前端框架·fastapi
SilentSamsara16 天前
模型部署实战:FastAPI + ONNX + Docker 的推理服务化
人工智能·pytorch·python·深度学习·机器学习·fastapi
放下华子我只抽RuiKe516 天前
FastAPI 全栈后端(七):测试与自动化
运维·前端·人工智能·react.js·前端框架·自动化·fastapi