API エンドポイントを1つ構築しましょう

Claude Code によるソフトウェア開発

Dani Zysman

AI Curriculum Manager @ DataCamp

クエリから API へ

recraft: half: Claude AI アシスタントと API を構築する開発者の机。画面にはコードとデータベース接続が表示されている

  • 前の動画: データベースに対話的にクエリを実行
  • 今回: Music Analytics API にエンドポイントを追加
    • 1つのプロンプトで、動作するエンドポイントと実際の Python コードを生成
Claude Code によるソフトウェア開発

ここまでのプロジェクト

music-analytics-api/
  app.py             # Existing API (updated to register db_routes)
  routes.py          # Existing routes
  models.py          # Artist/Album models
  db_routes.py       # <- New database-backed 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 によるソフトウェア開発

エッジケースに対応

  • こんな場合は?
    • アーティスト 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...