FastAPI极速入门:15分钟搭建你的首个智能API(附自动文档生成)🚀
title: FastAPI极速入门:15分钟搭建你的首个智能API(附自动文档生成)🚀
# 方案1:venv(Python原生)
python -m venv fastapi-env
source fastapi-env/bin/activate # Linux/Mac
fastapi-env\Scripts\activate # Windows
# 方案2:pipenv(推荐)
pip install pipenv
pipenv install fastapi uvicorn
# 方案3:poetry(进阶)
poetry new myapi
cd myapi
poetry add fastapi uvicorn
# pyproject.toml 示例(使用poetry)
[tool.poetry.dependencies]
python = "^3.8"
fastapi = "^0.115.10"
uvicorn = {extras = ["standard"], version = "^0.23.0"}
# 安装命令
poetry install # 自动解析依赖
# main.py
from fastapi import FastAPI
app = FastAPI(
title="智能天气API",
description="实时获取天气数据",
version="0.1.0"
)
@app.get("/weather/{city}")
async def get_weather(city: str, days: int = 7):
return {
"city": city,
"forecast": [
{"day": i+1, "temp": 25+i}
for i in range(days)
]
}
# 开发模式(热重载)
uvicorn main:app --reload
# 生产模式
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
@app.get(
"/weather/{city}",
summary="获取城市天气",
response_description="未来天气预测",
tags=["气象服务"]
)
async def get_weather(...):
...
# 要求:
# 1. 访问 /health 返回服务器状态
# 2. 包含服务器时间戳
# 3. 响应状态码200
@app.get("/health")
async def health_check():
# 你的代码
# 危险代码
@app.get("/user/{user_id}")
async def get_user(user_id: str):
query = f"SELECT * FROM users WHERE id = {user_id}"
# 任务:使用类型提示+参数化查询改写
错误现象 | 原因 | 解决方案 |
---|---|---|
ImportError: cannot import name 'FastAPI' | 未安装FastAPI | pip install fastapi |
Address already in use | 端口被占用 | 更换端口:uvicorn main:app --port 8001 |
422 Validation Error | 参数类型错误 | 检查路径参数和查询参数类型 |
评论
发表评论