技术学习
📚 快速上手新技术
场景:学习新的框架或库
你: 我想学习 FastAPI,给我一个快速入门指南
傻妞: FastAPI 快速入门:
安装:
```bash
pip install fastapi uvicornHello World:
python
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}运行:
bash
uvicorn main:app --reload核心概念:
- 路由(Path Operations)
python
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}- 请求体(Request Body)
python
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items")
def create_item(item: Item):
return item- 查询参数(Query Parameters)
python
@app.get("/items")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}- 自动文档 访问:https://fastapi.tiangolo.com
下一步实践:
- 创建 CRUD API
- 添加数据库
- 实现认证
- 编写测试
## API 文档理解
### 场景:理解复杂的 API 文档你: 帮我理解这个 API 文档:
POST /api/users
Content-Type: application/json
Request Body:
{
"name": string (required),
"email": string (required, format: email),
"age": integer (optional, min: 18, max: 120)
}
Response 201:
{
"id": integer,
"name": string,
"email": string,
"age": integer,
"created_at": datetime
}
Response 400:
{
"error": string
}傻妞: API 文档解析:
端点信息:
- 方法:POST
- 路径:/api/users
- 功能:创建新用户
请求说明:
必须字段:
- name:用户名(字符串)
- email:邮箱(必须符合邮箱格式)
可选字段:
- age:年龄(整数,18-120之间)
使用示例:
python
import requests
# 成功请求
response = requests.post('http://api.example.com/api/users', json={
"name": "张三",
"email": "zhangsan@example.com",
"age": 25
})
# 返回 201,包含用户信息
# 失败请求
response = requests.post('http://api.example.com/api/users', json={
"name": "李四"
# 缺少 email
})
# 返回 400,{"error": "email is required"}注意事项: ⚠️ email 是必填的,且必须符合格式 ⚠️ age 如果提供,必须在 18-120 之间 ⚠️ 成功返回 201 状态码 ⚠️ 失败返回 400 和错误信息
---
[上一篇:调试助手](./debugging.md) | [返回目录](./) | 下一篇:[代码转换](./conversion.md)