建立一個 API 端點

使用 Claude Code 進行軟體開發

Dani Zysman

AI Curriculum Manager @ DataCamp

從查詢到 API

在桌前的開發者,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 - New Flask Blueprint with:
    - get_db_connection() helper to connect to chinook.db
    - Added endpoint that queries the database for all albums by a specific artist
    - Returns JSON with AlbumId, Title, and ArtistId fields
2. Updated app.py 
    - Registered the blueprint so the new endpoint is active

The endpoint will return a 404 if the artist doesn't exist, 
and returns albums sorted by title as 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 進行軟體開發

處理邊界情況

  • 如果發生...
    • Artist 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.
Done! Added Pydantic validation to db_routes.py:
Changes:
- Added Album model (album_id, title, artist_id)
- Returns 404 "Artist not found" if artist doesn't exist
- Returns 404 "Artist has no albums" if artist has no albums
- Validates each album against Album model before returning
- Returns 400 on validation errors
Responses:
- 404 "Artist not found"
- 404 "Artist has no albums"  
- 200 with validated album data
使用 Claude Code 進行軟體開發

一起來練習吧!

使用 Claude Code 進行軟體開發

Preparing Video For Download...