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

相关推荐
kyle~5 天前
FastAPI --- 将业务能力以 API 的形式提供给外部系统
python·fastapi·前后端
MSTcheng.5 天前
【AI应用实战】用 FastAPI + SSE 做一个自己的 AI 聊天网页:流式输出、多轮对话与完整源码
人工智能·python·大模型·fastapi·sse·ai聊天助手
kevin_org6 天前
LangChain入门学习(四)
python·学习·langchain·fastapi
LK_0715 天前
【FastAPI】基础篇 01|开始之前:API、HTTP 与 FastAPI 到底是什么
网络协议·http·fastapi
一枕槐安48721 天前
Qwen 通义千问本地部署与推理服务封装
fastapi·qwen·vllm·流式推理·openai兼容api·awq量化
在努力的前端小白21 天前
基于FastAPI+LangChain+LangGraph+Agent+多模态的AI Agent 有渔渔具网站
人工智能·langchain·vue·fastapi
sun_weitao21 天前
用 FastAPI + MQTT 做一个 ESP32最小化跑通示例
中间件·vue·fastapi
峯58021 天前
一文学习FastAPI
学习·fastapi
TheBestRucy23 天前
从零构建企业级“中文法律智能问答系统”:FastAPI+Milvus+混合检索+真流式RAG实战
fastapi·milvus
卡提西亚24 天前
FastAPI基础入门
python·fastapi