入门攻略
MCP提交
探索
Fastapi Sample MCP Server
内容详情
替代品
什么是 FastAPI?
FastAPI 是一个高性能的网络应用框架,基于 Python 3.5+ 和 Pydantic v1.x 构建。它结合了现代 Web 开发的最佳实践和快速开发的理念,旨在帮助开发者高效地构建 RESTful API 和实时 Web 应用。
特点
- 高性能:FastAPI 使用 async/await 异步编程模型,使得处理高并发请求变得轻松。
- 简单易用:通过 Pydantic 模型和 Python 类型提示,可以快速定义 API 的请求和响应结构。
- 自动文档:内置 Swagger UI 和 ReDoc,无需额外配置即可生成交互式 API 文档。
- 可扩展性:支持中间件、自定义路由和插件,方便进行功能扩展。
安装
要开始使用 FastAPI,首先需要安装必要的依赖:
pip install fastapi[all]
这会安装 FastAPI 以及其所有依赖项,包括 Pydantic 和 Starlette。
创建第一个 API
创建一个简单的 FastAPI 应用:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
运行应用:
uvicorn main:app --reload
然后在浏览器中访问 http://localhost:8000
,可以看到自动生成的 Swagger UI。
请求参数
FastAPI 支持多种请求参数,包括路径参数、查询参数和请求体参数。
路径参数
@app.get("/items/{item_id}")
async def read_item(item_id: str):
return {"item_id": item_id}
访问 http://localhost:8000/items/5
会返回 {"item_id": "5"}
。
查询参数
@app.get("/items")
async def read_items(q: str = None):
if q:
return {"q": q}
else:
return {"message": "No query string received"}
访问 http://localhost:8000/items?q=hello
会返回 {"q": "hello"}
。
请求体参数
from typing import Optional
import json
@app.post("/items")
async def create_item(data: dict):
return data
发送一个 POST 请求到 /items
,请求体为:
{
"name": "item1",
"price": 10.5
}
会返回相同的 JSON 数据。
中间件
FastAPI 允许添加中间件来扩展功能。例如,可以添加日志记录中间件:
@app.middleware("http")
async def log_request(request, call_next):
print(f"Request received: {request.url}")
response = await call_next(request)
print(f"Response sent: {response.status_code}")
return response
自动文档
FastAPI 内置了 Swagger 和 ReDoc,方便开发者测试和查看 API 文档。
访问 http://localhost:8000/docs
可以看到交互式的 Swagger UI。
访问 http://localhost:8000/redoc
可以看到更详细的 ReDoc 文档。
总结
FastAPI 是一个强大且易于使用的 Web 框架,适合快速开发高性能的 RESTful API 和实时 Web 应用。通过其内置的文档生成和异步支持,开发者可以高效地构建和部署 Web 应用。