API 엔드포인트 하나 만들기

Claude Code로 배우는 Software Development

Dani Zysman

AI Curriculum Manager @ DataCamp

쿼리에서 API로

recraft: half: 책상에서 Claude AI 어시스턴트의 도움으로 API를 만드는 개발자, 화면에 데이터베이스 연결 코드가 표시된 모습

  • 이전 동영상: 데이터베이스를 대화형으로 쿼리했습니다
  • 이번에는: Music Analytics API에 엔드포인트를 추가합니다
    • 프롬프트 하나로 작동하는 엔드포인트와 실제 Python 코드를 만듭니다
Claude Code로 배우는 Software Development

지금까지의 프로젝트

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로 배우는 Software Development

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로 배우는 Software Development

생성된 코드

@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로 배우는 Software Development

로컬에서 테스트하기

$ 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로 배우는 Software Development

예외 상황 처리하기

  • 만약...
    • 아티스트 ID가 존재하지 않는다면?
    • 아티스트에게 앨범이 없다면?
    • ID 형식이 잘못됐다면?
    • 현재 코드는 빈 {"albums": []}를 반환합니다
  • 더 나은 응답:
    • 명확한 메시지와 함께 404 반환
    • 검증된 응답 구조
    • 적절한 오류 처리
Claude Code로 배우는 Software Development

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로 배우는 Software Development

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로 배우는 Software Development

연습해 봅시다!

Claude Code로 배우는 Software Development

Preparing Video For Download...