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

相关推荐
一枕槐安48711 小时前
Qwen 通义千问本地部署与推理服务封装
fastapi·qwen·vllm·流式推理·openai兼容api·awq量化
在努力的前端小白15 小时前
基于FastAPI+LangChain+LangGraph+Agent+多模态的AI Agent 有渔渔具网站
人工智能·langchain·vue·fastapi
sun_weitao21 小时前
用 FastAPI + MQTT 做一个 ESP32最小化跑通示例
中间件·vue·fastapi
峯5801 天前
一文学习FastAPI
学习·fastapi
TheBestRucy3 天前
从零构建企业级“中文法律智能问答系统”:FastAPI+Milvus+混合检索+真流式RAG实战
fastapi·milvus
卡提西亚4 天前
FastAPI基础入门
python·fastapi
Paper-Tiger4 天前
手搓 FastAPI + Redis + 流式 RAG 实录
fastapi
像风一样自由20204 天前
2.如何用FastAPI把一个Python算法封装成HTTP服务
python·算法·fastapi
狗凯之家源码网4 天前
iOS C2 V2 与 Python FastAPI 全链路远控系统深度评测
python·ios·fastapi
触底反弹5 天前
🚀 FastAPI 五大重难点深度剖析:从 500 报错到彻底搞懂 Depends、Pydantic 与 SQLAlchemy
python·fastapi