Python FastAPI

介绍

FastAPI 是 Python 里写 API 接口最快、最简单、最强的现代 Web 框架,写后端接口的 "超级工具包"https://fastapi.tiangolo.com/

  • 写接口速度极快
  • 自动生成文档 访问 /docs 自动出漂亮的接口页面
  • 自带数据校验
  • 性能接近 Go / Node
  • 代码超级简洁

FastAPI = Starlette(高性能 Web) + Pydantic(数据校验)

写一个最简单的接口

python 复制代码
# main.py
from fastapi import FastAPI

# 1. 创建 app
app = FastAPI()

# 2. 写接口(路径:/ ,GET请求)
@app.get("/")
def home():
    return {"message": "你好,FastAPI!"}

# 3. 再写一个接口
@app.get("/user")
def get_user():
    return {"name": "张三", "age": 20}

运行,Uvicorn 是 "高性能服务器",负责把接口暴露给别人访问,

  • Python 代码 → 交给 Python 解释器运行
  • FastAPI 应用 → 交给 Uvicorn 服务器运行

自动生成的接口文档地址

python 复制代码
#uvicorn:启动服务器
#main:去找 main.py 文件
#app:去找文件里的 app = FastAPI()
--reload:代码改了自动重启
uvicorn main:app --reload

最常用的写法是加上Pydantic一起用

python 复制代码
from pydantic import BaseModel

# 定义数据格式(你学过的 BaseModel)
class User(BaseModel):
    name: str
    age: int
    email: str

# 接收 JSON
@app.post("/add_user")
def add_user(user: User):
    # 直接用 user.name, user.age, user.email
    return {
        "msg": "添加成功",
        "name": user.name,
        "age": user.age
    }

FastAPI的生命周期

历史用法是,直接加入@app.on_event("startup")装饰器吗,现有的用法被整合到一起使用,

@asynccontextmanager,同时 也支持websocket @app.websocket

python 复制代码
from dotenv import load_dotenv
from fastapi import FastAPI
from langchain.agents import create_agent
from langchain_core.messages import HumanMessage
from langchain_mcp_adapters.client import MultiServerMCPClient
from pydantic import BaseModel
import uvicorn
from contextlib import asynccontextmanager  # 新增

load_dotenv()


agent = None
client = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    global agent, client
    # ====================== 【服务启动时执行】 ======================
    print("🚀 服务启动,初始化 AI 智能体...")

    client = MultiServerMCPClient(
        {
            "math": {
                "transport": "stdio",
                "command": "python",
                "args": [r"D:\project\pyproject\agent\tools\Math.py"],
            },
        }
    )
    tools = await client.get_tools()
    agent = create_agent(model="deepseek-chat", tools=tools)

    # 服务运行中
    yield

    # ====================== 【服务关闭时执行】 ======================
    print("服务关闭,清理资源...")
    if client is not None:
        await client.close()  # 优雅关闭客户端


app = FastAPI(
    title="LangChain Agent API",
    lifespan=lifespan
)


# ====================== 请求模型 ======================
class ChatRequest(BaseModel):
    question: str


# ====================== Java 调用接口 ======================
@app.post("/agent/chat")
async def chat(request: ChatRequest):
    response = await agent.ainvoke({
        "messages": [
            HumanMessage(content=request.question)
        ]
    })
    answer = response["messages"][-1].content
    return {
        "code": 200,
        "message": "success",
        "data": answer
    }


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