FastAPI+AI:构建高性能REST API服务

AI教程 2026-06-21

FastAPI是2026年最流行的Python Web框架。

安装

pip install fastapi uvicorn

基础API

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Query(BaseModel):
    text: str

@app.post("/analyze")
async def analyze(query: Query):
    return {"text": query.text, "length": len(query.text)}

@app.get("/health")
async def health():
    return {"status": "ok"}

集成AI模型

from transformers import pipeline
classifier = pipeline("sentiment-analysis")

@app.post("/sentiment")
async def sentiment(query: Query):
    r = classifier(query.text)[0]
    return {"sentiment": r["label"], "score": r["score"]}

启动

uvicorn main:app --host 0.0.0.0 --port 8000 --reload

参考:FastAPI官方文档 | 2026年06月21日

©️版权声明:若无特殊声明,本站所有文章版权均归AI工具集原创和所有,未经许可,任何个人、媒体、网站、团体不得转载、抄袭或以其他方式复制发表本站内容,或在非我站所属的服务器上建立镜像。否则,我站将依法保留追究相关法律责任的权利。

相关文章