构建一个 API 端点

使用 Claude Code 进行软件开发

Dani Zysman

AI Curriculum Manager @ DataCamp

从查询到 API

recraft: half: 一位开发者在桌前,Claude AI 助手协助构建 API,屏幕显示包含数据库连接的代码

  • 上个视频: 交互式查询数据库
  • 现在: 为 Music Analytics API 添加一个端点
    • 一条提示,产出可用端点与真实 Python 代码
使用 Claude Code 进行软件开发

项目现状

music-analytics-api/
  app.py             # 现有 API(更新以注册 db_routes)
  routes.py          # 现有路由
  models.py          # Artist/Album 模型
  db_routes.py       # <- 新的数据库驱动 Blueprint
  chinook.db
  test_routes.py
  CLAUDE.md
使用 Claude Code 进行软件开发

让 Claude 来构建

> Create a new db_routes.py blueprint with an endpoint at 
/artists/<artist_id>/albums that returns all albums by 
a specific artist as JSON from chinook,db. Register it with @app.py
1. db_routes py - 新建 Flask Blueprint,包含:
    - get_db_connection() 辅助函数连接 chinook.db
    - 新增端点,查询特定艺人的所有专辑
    - 返回包含 AlbumId、Title 和 ArtistId 字段的 JSON
2. 更新 app.py 
    - 注册该 blueprint,使新端点生效

若艺人不存在将返回 404,
并按标题排序返回专辑的 JSON。
使用 Claude Code 进行软件开发

生成的代码

@app.route("/artists/<int:artist_id>/albums")
def get_artist_albums(artist_id):
    conn = get_db()
    artist = conn.execute("SELECT ... WHERE ArtistId = ?", ...)
    albums = conn.execute("SELECT ... WHERE ArtistId = ?", ...)
    conn.close()
    return jsonify({"artist": ..., "albums": [...]})
使用 Claude Code 进行软件开发

本地测试

$ python app.py & PID=$! && sleep 3 && curl http://127.0.0.1:5000/artists/1/albums
&& kill $PID
127.0.0.1 "GET /artists/1/albums HTTP/1.1" 200
[
    {
     "album_id": 1,
     "artist_id": 1,
     "title": "For Those About To Rock We Salute You"
    },
    {
     "album_id": 4,
     "artist_id": 1,
     "title": "Let There Be Rock"
    }
]
使用 Claude Code 进行软件开发

处理边界情况

  • 如果……
    • 艺人 ID 不存在?
    • 艺人没有专辑?
    • ID 格式无效?
    • 现有代码返回空的 {"albums": []}
  • 更好的响应:
    • 404 且含清晰信息
    • 校验过的响应结构
    • 合理的错误处理
使用 Claude Code 进行软件开发

用 Pydantic 做校验

from pydantic import BaseModel
from typing import List

class Album(BaseModel):
    id: int
    title: str

class ArtistAlbums(BaseModel):
    artist_id: int
    albums: List[Album]
  • Pydantic 提供:
    • 类型校验
    • 自动序列化
    • 清晰的错误信息
    • 自文档化的模式
使用 Claude Code 进行软件开发

让 Claude 加入校验

> Add Pydantic validation to @db_routes.py. Return 404 with a message if the 
artist doesn't exist or has no albums.
完成!已在 db_routes.py 中加入 Pydantic 校验:
更改:
- 新增 Album 模型(album_id、title、artist_id)
- 若艺人不存在返回 404 "Artist not found"
- 若艺人没有专辑返回 404 "Artist has no albums"
- 返回前按 Album 模型校验每条专辑
- 校验出错返回 400
响应:
- 404 "Artist not found"
- 404 "Artist has no albums"  
- 200,包含已校验的专辑数据
使用 Claude Code 进行软件开发

让我们一起练习吧!

使用 Claude Code 进行软件开发

Preparing Video For Download...