SSP(Supply-Side Platform) API를 파이썬으로 구현하는 예제 250108
q1: SSP(Supply-Side Platform) API를 파이썬으로 구현하는 예제
a1:
SSP(Supply-Side Platform) API를 파이썬으로 구현하는 간단한 예제를 만들어보겠습니다. 이 예제는 기본적인 광고 인벤토리 관리 기능(생성, 조회, 수정, 삭제)과 광고 요청 처리를 포함합니다.
기능 설명
1. 광고 인벤토리 관리: 광고 슬롯을 추가, 조회, 수정, 삭제.
2. 광고 요청 처리: DSP(광고주 플랫폼)로부터 입찰 요청을 받아 가장 높은 입찰자를 선택.
3. 사용 기술: Python의 FastAPI를 사용해 REST API를 구현.
SSP API 예제 코드
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
# 광고 슬롯 모델
class AdSlot(BaseModel):
id: int
name: str
min_bid: float # 최소 입찰가
category: str # 광고 카테고리
is_active: bool = True
# 입찰 요청 모델
class BidRequest(BaseModel):
dsp_id: str # DSP 식별자
ad_slot_id: int
bid_price: float
advertiser: str
# 입찰 응답 모델
class BidResponse(BaseModel):
ad_slot_id: int
advertiser: str
winning_bid: float
# 데이터 저장 (간단한 메모리 저장소)
ad_slots: List[AdSlot] = []
bids: List[BidRequest] = []
# 기본 광고 슬롯 데이터
ad_slots.append(AdSlot(id=1, name="Top Banner", min_bid=1.0, category="Technology"))
ad_slots.append(AdSlot(id=2, name="Sidebar Ad", min_bid=0.5, category="Lifestyle"))
# 광고 슬롯 목록 조회
@app.get("/ad_slots", response_model=List[AdSlot])
def get_ad_slots(active_only: bool = Query(False, description="활성화된 슬롯만 조회")):
if active_only:
return [slot for slot in ad_slots if slot.is_active]
return ad_slots
# 광고 슬롯 생성
@app.post("/ad_slots", response_model=AdSlot)
def create_ad_slot(slot: AdSlot):
if any(existing_slot.id == slot.id for existing_slot in ad_slots):
raise HTTPException(status_code=400, detail="Ad slot ID already exists")
ad_slots.append(slot)
return slot
# 광고 슬롯 수정
@app.put("/ad_slots/{slot_id}", response_model=AdSlot)
def update_ad_slot(slot_id: int, updated_slot: AdSlot):
for i, slot in enumerate(ad_slots):
if slot.id == slot_id:
ad_slots[i] = updated_slot
return updated_slot
raise HTTPException(status_code=404, detail="Ad slot not found")
# 광고 슬롯 삭제
@app.delete("/ad_slots/{slot_id}")
def delete_ad_slot(slot_id: int):
global ad_slots
ad_slots = [slot for slot in ad_slots if slot.id != slot_id]
return {"message": "Ad slot deleted successfully"}
# 입찰 요청 처리
@app.post("/bid", response_model=Optional[BidResponse])
def handle_bid(bid: BidRequest):
# 광고 슬롯 확인
slot = next((slot for slot in ad_slots if slot.id == bid.ad_slot_id), None)
if not slot:
raise HTTPException(status_code=404, detail="Ad slot not found")
# 최소 입찰가 확인
if bid.bid_price < slot.min_bid:
return {"message": "Bid price is below the minimum bid price for the ad slot"}
# 현재 입찰 추가
bids.append(bid)
# 가장 높은 입찰을 선택
highest_bid = max(
(b for b in bids if b.ad_slot_id == bid.ad_slot_id),
key=lambda x: x.bid_price,
default=None
)
if highest_bid:
return BidResponse(
ad_slot_id=highest_bid.ad_slot_id,
advertiser=highest_bid.advertiser,
winning_bid=highest_bid.bid_price
)
else:
return None
# 입찰 내역 조회 (관리자용)
@app.get("/bids", response_model=List[BidRequest])
def get_bids(ad_slot_id: Optional[int] = Query(None, description="특정 광고 슬롯의 입찰만 조회")):
if ad_slot_id:
return [bid for bid in bids if bid.ad_slot_id == ad_slot_id]
return bids
# 서버 상태 확인 (헬스 체크)
@app.get("/health")
def health_check():
return {"status": "OK"}
예제 실행 방법
1. 코드 저장
위 코드를 ssp_api.py로 저장합니다.
2. FastAPI 실행
FastAPI 서버를 실행하려면 아래 명령어를 사용하세요:
uvicorn ssp_api:app --reload
3. API 테스트
서버가 실행되면 브라우저 또는 Postman에서 API를 호출하거나 http://127.0.0.1:8000/docs에서 Swagger 문서를 확인할 수 있습니다.
API 사용 예시
1. 광고 슬롯 생성
• POST /ad_slots
• 요청 본문:
{
"id": 3,
"name": "Footer Banner",
"min_bid": 0.8,
"category": "Entertainment",
"is_active": true
}
2. 광고 슬롯 조회
• GET /ad_slots?active_only=true
활성화된 광고 슬롯만 반환.
3. 입찰 요청
• POST /bid
• 요청 본문:
{
"dsp_id": "dsp123",
"ad_slot_id": 1,
"bid_price": 1.5,
"advertiser": "Advertiser A"
}
4. 입찰 내역 확인
• GET /bids?ad_slot_id=1
특정 광고 슬롯의 모든 입찰 내역을 반환.
확장 가능성
이 코드는 SSP API의 기본적인 구조만 구현한 것으로, 다음과 같은 기능을 추가하여 확장할 수 있습니다:
1. RTB(실시간 입찰): DSP와 실시간 통신하여 입찰 과정을 처리.
2. 통계 및 분석: 입찰 성과 데이터를 집계하여 퍼블리셔에게 제공.
3. 보안: JWT 인증을 추가해 사용자 권한 관리.
4. 캐싱: 광고 슬롯 및 입찰 데이터를 Redis와 같은 캐시를 사용해 최적화.
이 코드는 간단한 예제이므로 실제 시스템에서는 더 많은 성능 최적화와 보안 기능이 필요할 수 있습니다.