메인 콘텐츠로 건너뛰기
X API는 모든 엔드포인트에 인증을 요구합니다. XDK는 세 가지 인증 방식을 지원합니다:
  1. Bearer 토큰 (앱 전용)
  2. OAuth 2.0 with PKCE
  3. OAuth 1.0a (사용자 컨텍스트)
  • Bearer Token: 앱 인증을 지원하는 엔드포인트(예: 게시물 검색, 스트리밍 엔드포인트)에 대한 읽기 전용 액세스에 사용합니다.
  • OAuth 2.0 PKCE: 스코프 기반의 사용자 승인 액세스를 위한 안전한 인증 방식입니다(예: 인증된 사용자의 게시물 non_public 메트릭 가져오기).
  • OAuth 1.0a: 사용자별 작업(예: 사용자를 대신해 게시물 작성, 리스트 관리)을 위한 레거시 인증입니다. X 개발자 콘솔에서 자격 증명을 발급받으세요. 승인된 개발자 계정과 적절한 권한(예: 읽기 + 쓰기)을 가진 앱이 필요합니다.

Client 생성하기

모든 인증 플로우는 Client 인스턴스를 생성합니다.
from xdk import Client

1. Bearer Token (App-Only)

읽기 전용 작업을 사용자 컨텍스트 없이 수행할 때 사용합니다. 단계:
  1. 개발자 콘솔에서 App용 Bearer 토큰을 생성합니다.
  2. 생성한 토큰을 Client에 전달합니다. 예시:
client = Client(bearer_token="XXXXX")
사용 방법:
# search_recent은 Iterator를 반환하므로 이를 반복합니다
for page in client.posts.search_recent(query="python", max_results=10):
    if page.data and len(page.data) > 0:
        first_post = page.data[0]
        post_text = first_post.text if hasattr(first_post, 'text') else first_post.get('text', '')
        print(post_text)  # 첫 번째 포스트에 접근
        break

2. OAuth 2.0 with PKCE (사용자 컨텍스트)

이 예제는 Proof Key for Code Exchange(PKCE)를 사용하는 OAuth 2.0 흐름을 보여줍니다. 이를 사용자별 액세스(예: 사용자를 대신해 게시물 작성), 특정 사용자의 미디어 업로드 등에 사용합니다. 단계:
  1. 개발자 콘솔에서 리디렉트 URI(예: http://localhost:8080/callback)와 함께 App을 등록합니다.
  2. Client ID를 발급받습니다(PKCE에는 secret이 필요하지 않습니다).
  3. 플로우를 시작하고, 사용자를 인증 URL로 리디렉션한 뒤 콜백을 처리합니다. 예시 (콜백 처리를 위해 웹 서버를 사용하는 경우):
from xdk.oauth2_auth import OAuth2PKCEAuth
from urllib.parse import urlparse
import webbrowser
# Step 1: Create PKCE instance
auth = OAuth2PKCEAuth(
    client_id="YOUR_CLIENT_ID",
    redirect_uri="YOUR_CALLBACK_URL",
    scope="tweet.read users.read offline.access"
)
# Step 2: Get authorization URL
auth_url = auth.get_authorization_url()
print(f"Visit this URL to authorize: {auth_url}")
webbrowser.open(auth_url)
# 3단계: 콜백 처리 (실제 앱에서는 Flask와 같은 웹 프레임워크 사용)
# callback_url = "http://localhost:8080/callback?code=AUTH_CODE_HERE"라고 가정
callback_url = input("Paste the full callback URL here: ")
# Step 4: Exchange code for tokens
tokens = auth.fetch_token(authorization_response=callback_url)
access_token = tokens["access_token"]
refresh_token = tokens["refresh_token"]  # Store for renewal
# Step 5: Create client
# Option 1: Use bearer_token (OAuth2 access tokens work as bearer tokens)
client = Client(bearer_token=access_token)
# Option 2: Pass the full token dict for automatic refresh support
# client = Client(token=tokens)
토큰 갱신 (장기 세션에서는 SDK에서 자동으로 처리됨):
# If access token expires, refresh using stored refresh_token
# refresh_token 메서드는 OAuth2PKCEAuth 인스턴스에 저장된 토큰을 사용합니다
tokens = auth.refresh_token()
# Use the refreshed token
client = Client(bearer_token=tokens["access_token"])
# Or pass the full token dict: client = Client(token=tokens)

3. OAuth 1.0a (User Context)

레거시 애플리케이션 또는 OAuth 1.0a 인증이 필요한 특정 사용 사례의 경우: 단계:
  1. 개발자 콘솔에서 API Key와 API Secret을 가져옵니다.
  2. 이미 액세스 토큰이 있다면 그대로 사용합니다. 없다면 OAuth 1.0a 플로우를 완료해 액세스 토큰을 발급받습니다.
  3. OAuth1 인스턴스를 생성하고 이를 Client에 전달합니다. 예시 (기존 액세스 토큰이 있는 경우):
from xdk import Client
from xdk.oauth1_auth import OAuth1
# 1단계: 자격 증명을 사용하여 OAuth1 인스턴스 생성
oauth1 = OAuth1(
    api_key="YOUR_API_KEY",
    api_secret="YOUR_API_SECRET",
    callback="http://localhost:8080/callback",
    access_token="YOUR_ACCESS_TOKEN",
    access_token_secret="YOUR_ACCESS_TOKEN_SECRET"
)
# Step 2: Create client with OAuth1
client = Client(auth=oauth1)
# Step 3: Use the client
response = client.users.get_me()
me = response.data
print(me)
예시 (전체 OAuth 1.0a 흐름):
from xdk import Client
from xdk.oauth1_auth import OAuth1
import webbrowser
# Step 1: Create OAuth1 instance
oauth1 = OAuth1(
    api_key="YOUR_API_KEY",
    api_secret="YOUR_API_SECRET",
    callback="http://localhost:8080/callback"
)
# Step 2: Get request token
request_token = oauth1.get_request_token()
# Step 3: Get authorization URL
auth_url = oauth1.get_authorization_url(login_with_x=False)
print(f"Visit this URL to authorize: {auth_url}")
webbrowser.open(auth_url)
# 4단계: 사용자가 인증하고 oauth_verifier를 받습니다
# 실제 앱에서는 콜백 URL을 통해 처리합니다
oauth_verifier = input("Enter the OAuth verifier from the callback: ")
# Step 5: Exchange for access token
access_token = oauth1.get_access_token(oauth_verifier)
# Step 6: Create client
client = Client(auth=oauth1)
# Now you can use the client
response = client.users.get_me()
참고:
  • 운영 환경에서는 시크릿을 절대로 하드코딩하지 말고, 환경 변수나 시크릿 관리자(예: os.getenv("X_BEARER_TOKEN"))를 사용하세요.
  • PKCE를 사용할 때는 운영 환경에서 리디렉션 URI에 반드시 HTTPS를 사용하도록 하세요.
  • SDK는 토큰의 유효성을 검사하고, 실패 시 xdk.AuthenticationError를 발생시킵니다. Python XDK를 사용하는 더 자세한 코드 예시는 코드 샘플 GitHub 리포지토리를 참고하세요.