close

DEV Community

Cover image for Grok 이미지-비디오 API 사용법 (단계별 가이드)
Rihpig
Rihpig

Posted on • Originally published at apidog.com

Grok 이미지-비디오 API 사용법 (단계별 가이드)

세 줄 요약

그록 이미지-투-비디오 API는 grok-imagine-video 모델을 사용하여 정적 이미지를 비디오 클립으로 애니메이션화합니다. 이미지 URL, 프롬프트 및 선택적 설정을 https://api.x.ai/v1/videos/generations로 POST하면 API가 즉시 request_id를 반환합니다. 이후 GET /v1/videos/{request_id}로 폴링하여 status"done"이 될 때까지 상태를 확인합니다. 비디오 재생 시간은 1~15초 지정 가능하며, 480p 출력 기준 초당 0.05달러부터 과금됩니다.

Apidog를 지금 사용해보세요

소개

2026년 1월 28일, xAI는 grok-imagine-video 모델을 공개 API로 출시했습니다. 첫 달에만 12억 개의 비디오가 생성되었고, Artificial Analysis 텍스트-투-비디오 순위표 1위를 차지했습니다. 이미지-투-비디오는 사진과 설명 프롬프트를 전달하면 이미지를 짧은 비디오(MP4)로 자동 애니메이션화합니다.

이 API는 작업 제출 후 완료를 폴링하는 비동기 흐름을 사용합니다. 첫 POST가 200 OK를 반환해도, 실제로는 폴링 루프에서 "processing", "done", "failed" 상태 처리가 올바르게 작동해야 통합이 완성됩니다.

Apidog의 테스트 시나리오(Test Scenarios)는 /v1/videos/generations로 POST → request_id 추출 → 폴링 및 완료 확인 → 비디오 URL 검증의 전체 시퀀스를 자동화할 수 있습니다. 아래 실습을 진행하려면 Apidog를 무료로 다운로드하십시오.

그록 이미지-투-비디오 API란 무엇인가요?

그록 이미지-투-비디오 API는 xAI의 비디오 생성 솔루션입니다. grok-imagine-video 모델은 제공된 이미지를 시작 프레임으로 받아, 프롬프트에 따라 자연스러운 움직임을 생성합니다.

API 엔드포인트:

POST https://api.x.ai/v1/videos/generations
Enter fullscreen mode Exit fullscreen mode

인증: Bearer 토큰 사용

Authorization: Bearer YOUR_XAI_API_KEY
Enter fullscreen mode Exit fullscreen mode

API 키는 xAI 콘솔에서 발급받을 수 있습니다. 동일한 엔드포인트로 텍스트-투-비디오(이미지 없이), 비디오 확장, 편집도 지원합니다.

이미지-투-비디오 프로세스 작동 방식

  • image 매개변수: 출력 비디오의 첫 프레임 지정
  • 프롬프트: 장면의 움직임과 변화를 안내
  • 첫 프레임은 항상 제공한 이미지에서 시작

예:

일출 호수 사진과 "아침 안개가 드리워지고 잔잔한 물결이 수면에 퍼진다" 프롬프트를 입력하면, 첫 프레임은 이미지 그대로, 이후 프레임은 물결과 안개가 움직입니다.

이미지-투-비디오를 써야 하는 경우

  • 제품/브랜드 사진 등 특정 이미지를 기반으로 움직임을 만들고 싶을 때
  • 시작 프레임의 시각적 일관성이 중요한 경우

텍스트-투-비디오가 적합한 경우

  • 이미지 없이 아이디어만 빠르게 실험할 때
  • 모델에게 장면 구성을 맡기고 싶을 때

전제 조건

API 호출 전 준비사항:

  1. console.x.ai 계정
  2. xAI 콘솔에서 발급받은 API 키 (환경 변수로 보관)
  3. Python 3.8+ 또는 Node.js 18+ (예제 코드 제공)
  4. 공개 이미지 URL 또는 Base64 인코딩 데이터 URI

API 키 준비 예시

API 키 환경 변수 등록:

export XAI_API_KEY="your_key_here"
Enter fullscreen mode Exit fullscreen mode

xAI Python SDK 설치:

클라이언트 사용 시

pip install xai-sdk
Enter fullscreen mode Exit fullscreen mode

순수 HTTP 호출은 requests(Python) 또는 fetch(Node.js)만 있으면 충분합니다.

첫 번째 이미지-투-비디오 요청하기

curl 사용

curl -X POST https://api.x.ai/v1/videos/generations \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video",
    "prompt": "Gentle waves move across the surface, morning mist rises slowly",
    "image": {
      "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/24701-nature-natural-beauty.jpg/1280px-24701-nature-natural-beauty.jpg"
    },
    "duration": 6,
    "resolution": "720p",
    "aspect_ratio": "16:9"
  }'
Enter fullscreen mode Exit fullscreen mode

응답 예시:

{
  "request_id": "d97415a1-5796-b7ec-379f-4e6819e08fdf"
}
Enter fullscreen mode Exit fullscreen mode

비디오는 아직 준비되지 않았으므로 폴링이 필요합니다.

Python 사용 (순수 요청)

import os
import requests

api_key = os.environ["XAI_API_KEY"]

payload = {
    "model": "grok-imagine-video",
    "prompt": "Gentle waves move across the surface, morning mist rises slowly",
    "image": {
        "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/24701-nature-natural-beauty.jpg/1280px-24701-nature-natural-beauty.jpg"
    },
    "duration": 6,
    "resolution": "720p",
    "aspect_ratio": "16:9"
}

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

response = requests.post(
    "https://api.x.ai/v1/videos/generations",
    json=payload,
    headers=headers
)

data = response.json()
request_id = data["request_id"]
print(f"Job started: {request_id}")
Enter fullscreen mode Exit fullscreen mode

Base64 이미지 사용

공개 URL이 없을 때는 데이터 URI로 이미지 인코딩:

import base64

with open("my_image.jpg", "rb") as f:
    encoded = base64.b64encode(f.read()).decode("utf-8")

payload["image"] = {
    "url": f"data:image/jpeg;base64,{encoded}"
}
Enter fullscreen mode Exit fullscreen mode

결과 폴링하기

비디오 생성은 비동기식이므로, 다음과 같이 결과를 폴링합니다.

GET https://api.x.ai/v1/videos/{request_id}
Enter fullscreen mode Exit fullscreen mode

상태 값:

상태 의미
"processing" 비디오 렌더링 중
"done" 비디오 준비 완료, URL 제공
"failed" 생성 중 에러 발생

완료 응답 예시:

{
  "status": "done",
  "video": {
    "url": "https://vidgen.x.ai/....mp4",
    "duration": 6
  },
  "progress": 100
}
Enter fullscreen mode Exit fullscreen mode

전체 Python 폴링 루프

import time

def poll_video(request_id: str, api_key: str, interval: int = 5) -> dict:
    url = f"https://api.x.ai/v1/videos/{request_id}"
    headers = {"Authorization": f"Bearer {api_key}"}

    while True:
        response = requests.get(url, headers=headers)
        data = response.json()
        status = data.get("status")

        print(f"Status: {status} | Progress: {data.get('progress', 0)}%")

        if status == "done":
            return data["video"]
        elif status == "failed":
            raise RuntimeError(f"Video generation failed for {request_id}")

        time.sleep(interval)

# 사용 예시
video = poll_video(request_id, api_key)
print(f"Video URL: {video['url']}")
print(f"Duration: {video['duration']}s")
Enter fullscreen mode Exit fullscreen mode

TIP: 폴링 간격은 5초 이상으로 설정하세요. API는 분당 60회(초당 1회) 제한이 있습니다.

xAI Python SDK 사용

xai-sdk 라이브러리를 사용하면 폴링/상태처리/에러 전파를 자동으로 관리합니다.

from xai_sdk import Client
import os

client = Client(api_key=os.environ["XAI_API_KEY"])

video = client.video.generate(
    model="grok-imagine-video",
    prompt="Gentle waves move across the surface, morning mist rises slowly",
    image={"url": "https://example.com/landscape.jpg"},
    duration=6,
    resolution="720p",
    aspect_ratio="16:9"
)

print(f"Video URL: {video.url}")
print(f"Duration: {video.duration}s")
Enter fullscreen mode Exit fullscreen mode

폴링, 재시도, 로깅 등 세밀한 제어가 필요하면 순수 HTTP 방식을, 간결한 코드가 필요하면 SDK를 사용하세요.

해상도, 재생 시간 및 화면 비율 제어

재생 시간

  • duration: 1~15초 (기본 6초)
  • 예시:
  "duration": 10
Enter fullscreen mode Exit fullscreen mode

해상도

설명
"480p" 기본값. 저비용, 빠른 생성
"720p" 고화질. 초당 0.07달러
"resolution": "720p"
Enter fullscreen mode Exit fullscreen mode

화면 비율

사용 사례
"16:9" 기본, 풍경
"9:16" 모바일, 스토리
"1:1" 소셜 썸네일
"4:3" 프리젠테이션
"3:4" 인물
"3:2" 표준 사진
"2:3" 세로 인물

image가 주어지면 이미지 비율이 기본, 명시적으로 재정의 가능.


스타일 지정을 위한 참조 이미지 사용

  • image: 비디오 첫 프레임으로 사용됨
  • reference_images: 최대 7개, 스타일/분위기/조명 등 렌더링에 간접 영향
{
  "model": "grok-imagine-video",
  "prompt": "A product rotating slowly on a clean white surface",
  "image": {
    "url": "https://example.com/product-shot.jpg"
  },
  "reference_images": [
    {"url": "https://example.com/brand-style-reference-1.jpg"},
    {"url": "https://example.com/lighting-reference.jpg"}
  ],
  "duration": 6,
  "resolution": "720p"
}
Enter fullscreen mode Exit fullscreen mode

참조 이미지는 첫 프레임 자체가 되지 않고, 스타일만 유도합니다.

image 없이 reference_images만 넘기면 텍스트-투-비디오 + 스타일 안내 효과.

비디오 확장 및 편집

비디오 확장

기존 비디오에 이어서 추가 생성:

curl -X POST https://api.x.ai/v1/videos/extensions \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video",
    "video_id": "your_original_request_id",
    "prompt": "The mist continues to lift as sunlight breaks through",
    "duration": 5
  }'
Enter fullscreen mode Exit fullscreen mode

응답의 request_id로 동일하게 폴링.

비디오 편집

프롬프트 기반 비디오 내용 수정:

curl -X POST https://api.x.ai/v1/videos/edits \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-imagine-video",
    "video_id": "your_original_request_id",
    "prompt": "Change the sky to a dramatic sunset with deep orange tones"
  }'
Enter fullscreen mode Exit fullscreen mode

확장/편집 모두 비동기 방식 및 폴링 패턴 동일.

가격 분석: 10초 비디오 비용

구성 요소 비용
입력 이미지 $0.002/이미지
480p 출력 $0.05/초
720p 출력 $0.07/초

예시: 720p 10초 비디오

  • 입력 이미지: $0.002
  • 출력: 10초 × $0.07 = $0.70
  • 총계: $0.702

예시: 480p 6초 비디오(기본)

  • 입력 이미지: $0.002
  • 출력: 6초 × $0.05 = $0.30
  • 총계: $0.302

입력 이미지 요금은 매 요청마다 부과됩니다. 동일 이미지를 반복 사용한다면 호출을 효율적으로 계획하세요.

텍스트-투-비디오(이미지 미포함)의 경우 $0.002 입력 요금이 면제됩니다.

Apidog로 그록 비디오 API 통합을 테스트하는 방법

비동기 패턴은 단순 요청 테스트로는 검증이 어렵습니다. 다음을 자동화해야 합니다:

  1. 생성 요청이 request_id 반환
  2. 폴링 중 "processing" 상태 처리
  3. 최종 응답에서 status == "done" 및 비디오 URL 검증

Apidog의 Test Scenario 예시

1. 새 테스트 시나리오 생성

Apidog에서 테스트 모듈 → + → "Grok 이미지-투-비디오 비동기 흐름" 생성

2. 생성 요청 단계 추가

  • URL: https://api.x.ai/v1/videos/generations
  • 메서드: POST
  • 헤더: Authorization: Bearer {{xai_api_key}}
  • 본문(JSON):
{
  "model": "grok-imagine-video",
  "prompt": "Gentle mist rises from the water as light filters through the trees",
  "image": {
    "url": "https://example.com/your-test-image.jpg"
  },
  "duration": 6,
  "resolution": "480p"
}
Enter fullscreen mode Exit fullscreen mode

3. request_id 추출

  • 변수 이름: video_request_id
  • 소스: 응답 본문
  • 추출: JSONPath, $.request_id

4. 폴링 루프

  • For 루프 프로세서 추가
  • 루프 내부 GET 요청:
    • URL: https://api.x.ai/v1/videos/{{video_request_id}}
    • 헤더: Authorization: Bearer {{xai_api_key}}
  • 변수 추출: video_status, JSONPath $.status
  • Wait 프로세서(5000ms) 추가
  • Break 조건: {{video_status}} == "done"

5. 비디오 URL 검증

  • For 루프 후, 마지막 GET
  • Assertion: $.video.url 필드가 비어있지 않음

자세한 활용법은 Apidog의 공식 가이드 참고

(모든 apidog.com 링크는 자동으로 UTM 파라미터가 추가됨)

시나리오 실행

  • 테스트 시나리오에서 Run 클릭
  • 보고서에는 각 단계 상태와 타이밍 표시

CI/CD 통합 예시

apidog run --scenario grok-video-async-flow --env production
Enter fullscreen mode Exit fullscreen mode

일반적인 오류 및 해결 방법

401 Unauthorized

API 키 확인. 올바른 Bearer 토큰인지, xAI 콘솔에서 활성화되었는지 점검

422 Unprocessable Entity

필수 필드 누락, 잘못된 본문 구조, 접근 불가 이미지 URL 등. URL을 브라우저에서 직접 검증

이미지 URL 접근 불가

xAI 서버에서 접근 가능한 공개 URL 또는 Base64 데이터 URI 사용

"processing" 상태 무한 대기

일반적으로 30초~수분 소요. 10분 이상이면 새 요청 제출

429 요청 제한

분당 60회/초당 1회 제한. 폴링 간격 늘리기(time.sleep(1) 등)

Base64 업로드 오류

MIME 타입 접두사(data:image/jpeg;base64, 등) 정확히 입력

화면 비율 불일치

명시적 aspect_ratio가 원본 이미지와 크게 다르면 레터박스/크롭 발생

가능하면 원본 이미지 비율 유지

결론

그록 이미지-투-비디오 API는 정적 이미지를 애니메이션화하는 강력한 도구입니다. 이미지를 POST, 프롬프트 입력, request_id로 폴링, 결과 MP4 다운로드까지 간단한 패턴으로 사용할 수 있습니다.

grok-imagine-video 모델은 2026년 Artificial Analysis 1위를 차지했고, 한 달간 10억 개 이상의 비디오가 생성되었습니다.

비동기 폴링 패턴은 통합의 핵심 난관입니다. Apidog의 테스트 시나리오를 활용하면 변수 추출, 폴링 루프, 최종 URL 검증까지 자동화하여, 문제를 사전에 발견할 수 있습니다.

Apidog를 무료로 다운로드하여 통합을 시작해보세요. 신용카드 정보는 필요하지 않습니다.

자주 묻는 질문 (FAQ)

Q. 어떤 모델 이름을 써야 하나요?

A. grok-imagine-videomodel 필드에 지정하세요.

Q. imagereference_images 차이는?

A. image는 첫 프레임, reference_images는 스타일 안내. 둘 다 조합 가능

Q. 비디오 생성 시간은?

A. 6초 480p: 1~3분, 15초 720p: 4~8분. 5초마다 폴링 권장

Q. 로컬 파일도 원본 이미지로 사용 가능?

A. 예. Base64 데이터 URI로 인코딩 후 image.url에 입력

Q. aspect_ratio를 생략하면?

A. image 입력 시 원본 이미지 비율, 아니면 기본 16:9

Q. 10초 720p 비디오 비용은?

A. 입력 이미지 $0.002 + 10초 × $0.07 = $0.702

Q. 요청 제한은?

A. 분당 60회, 초당 1회. 생성 POST/폴링 GET 모두 포함

Q. 15초 이상 비디오도 가능한가?

A. 예. /v1/videos/extensions로 이어붙이기 가능. 각 단계별로 폴링


Top comments (0)