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

相关推荐
空空dream2 小时前
07 | FastAPI + llama.cpp 接入 Langfuse监控Prompt请求
prompt·fastapi·llama
cui_ruicheng5 小时前
FastAPI 应用开发(五)——SQLAlchemy ORM、APIRouter 与 Alembic 数据库迁移
python·fastapi·web
空空dream6 小时前
06 | Prometheus打通FastAPI云原生数据采集
云原生·prometheus·fastapi
梦想不只是梦与想7 小时前
SQLAlchemy:异步、连接池 (四)
数据库·fastapi·sqlalchemy
the局外人1 天前
FastAPI中jwt的基本使用与实践
后端·python·fastapi
Java后端的Ai之路1 天前
07React_Props验证器
人工智能·python·react.js·架构·fastapi
云和数据.ChenGuang2 天前
Codex 下载与本地部署实战:从零搭建你的 AI 编程助手
人工智能·深度学习·机器学习·语言模型·fastapi
Guarding and trust2 天前
项目拆解(二):模型输出是‘野‘的——三层兜底+重分析,把AI变成可靠零件
java·人工智能·python·大模型·fastapi·ollama·错误兜底
Sand(ContextGate)2 天前
从零搭建电商智能导购 Agent:LangGraph 编排 + 三层记忆 + 熔断降级 + 生产部署全链路实战
redis·agent·fastapi·电商·chromadb·langgraph·智能导购
余槐i3 天前
无慢查询 RT 却飙升:cProfile 定位 FastAPI 事件循环阻塞
后端·python·性能优化·fastapi·asyncio