チュートリアルに戻る
APIadvanced
18分

Sora 2 API 統合ガイド

完全なコード例とベストプラクティスで、Sora 2 API をあなたのアプリにシームレスに統合する方法を学びます。

著者: Sora2Everything チーム · 2025-10-12

Sora2 API完全ドキュメント:統合チュートリアルとコード例

Sora2 APIの使い方:はじめに

Sora 2 API は、開発者がプログラムから AI 動画を生成できるようにし、自動化されたコンテンツ制作、ワークフロー統合、スケーラブルな映像プロダクションの可能性を広げます。このSora2 APIガイドでは、セットアップから本番デプロイまでを網羅的に解説します。

学べること

  • API 認証の設定
  • 最初の API リクエストの実行
  • 生成の高度なパラメータ
  • 動画出力の管理
  • エラー処理とレート制限
  • 本番運用のベストプラクティス
  • 実運用の統合例

前提条件

  • Sora へのアクセス権を持つ OpenAI API アカウント
  • 基本的なプログラミング知識(Python または JavaScript)
  • REST API の理解
  • async/await パターンへの馴染み

Sora2 APIの使い方:認証とセットアップ

API アクセス

Sora 2 API は現在、以下のユーザーが利用できます。

  • 承認済みアクセスを持つ OpenAI API ユーザー
  • ChatGPT Pro 契約者(1 日 20 リクエスト)
  • 企業顧客(カスタム上限)

料金(2025 年 10 月時点):

  • 生成動画 1 秒あたり:$0.10
  • 5 秒動画:$0.50
  • 20 秒動画:$2.00
  • 60 秒動画:$6.00

認証

ステップ 1:API キーを取得

  1. platform.openai.com/api-keys にアクセス
  2. 「Create new secret key」をクリック
  3. 名前を付ける(例:「Sora Integration」)
  4. キーをコピーして安全に保管

ステップ 2:環境をセットアップ

# OpenAI SDK をインストール
npm install openai
# または
pip install openai
// JavaScript/Node.js
import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY
});
# Python
from openai import OpenAI

client = OpenAI(
    api_key=os.environ.get("OPENAI_API_KEY")
)

Sora2 APIチュートリアル:最初の動画生成リクエスト

最初の動画生成

JavaScript 例

async function generateVideo() {
  try {
    const video = await openai.videos.generate({
      model: "sora-2",
      prompt: "A golden retriever playing in a sunny garden",
      duration: 10,
      resolution: "1080p",
      aspect_ratio: "16:9"
    });

    console.log("Video URL:", video.url);
    return video;
  } catch (error) {
    console.error("Error:", error);
  }
}

Python 例

def generate_video():
    try:
        video = client.videos.generate(
            model="sora-2",
            prompt="A golden retriever playing in a sunny garden",
            duration=10,
            resolution="1080p",
            aspect_ratio="16:9"
        )

        print(f"Video URL: {video.url}")
        return video
    except Exception as error:
        print(f"Error: {error}")

レスポンスオブジェクト

{
  "id": "video_abc123",
  "object": "video",
  "created": 1704672000,
  "model": "sora-2",
  "status": "processing",
  "prompt": "A golden retriever playing in a sunny garden",
  "duration": 10,
  "resolution": "1080p",
  "aspect_ratio": "16:9",
  "url": null,
  "expires_at": 1704758400
}

Sora2 API高度なパラメータ:動画生成のカスタマイズ

生成オプション

const advancedVideo = await openai.videos.generate({
  // 必須
  model: "sora-2",
  prompt: "Your detailed prompt here",

  // 長さ(5〜60 秒)
  duration: 20,

  // 解像度
  resolution: "1080p", // "480p", "720p", "1080p"

  // アスペクト比
  aspect_ratio: "16:9", // "16:9", "9:16", "1:1", "21:9"

  // フレームレート
  fps: 30, // 24 または 30

  // 任意:再現性のためのシード値
  seed: 12345,

  // 任意:バリエーション数
  n: 1, // 1〜4

  // 任意:品質設定
  quality: "standard", // "standard" または "hd"

  // 任意:非同期通知の Webhook
  webhook_url: "https://yourapi.com/webhook",

  // 任意:カスタムメタデータ
  metadata: {
    project: "Marketing Campaign Q1",
    user_id: "user_123"
  }
});

アスペクト比ガイド

const aspectRatios = {
  "16:9": {
    use_cases: ["YouTube", "Website", "Presentations"],
    dimensions: "1920x1080"
  },
  "9:16": {
    use_cases: ["TikTok", "Instagram Reels", "Stories"],
    dimensions: "1080x1920"
  },
  "1:1": {
    use_cases: ["Instagram Feed", "Social Media"],
    dimensions: "1080x1080"
  },
  "21:9": {
    use_cases: ["Cinematic", "Ultra-wide"],
    dimensions: "2560x1080"
  }
};

完了までのポーリング

動画は非同期で生成されるため、完了をポーリングする必要があります。

JavaScript 実装

async function waitForVideo(videoId) {
  const maxAttempts = 60; // 最大 10 分
  const pollInterval = 10000; // 10 秒間隔

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const video = await openai.videos.retrieve(videoId);

    if (video.status === "completed") {
      return video;
    } else if (video.status === "failed") {
      throw new Error(`Video generation failed: ${video.error}`);
    }

    // 次のポーリングまで待機
    await new Promise(resolve => setTimeout(resolve, pollInterval));
  }

  throw new Error("Video generation timed out");
}

// 使い方
const video = await generateVideo();
const completedVideo = await waitForVideo(video.id);
console.log("Video ready:", completedVideo.url);

Python 実装

import time

def wait_for_video(video_id):
    max_attempts = 60  # 最大 10 分
    poll_interval = 10  # 10 秒

    for attempt in range(max_attempts):
        video = client.videos.retrieve(video_id)

        if video.status == "completed":
            return video
        elif video.status == "failed":
            raise Exception(f"Video generation failed: {video.error}")

        time.sleep(poll_interval)

    raise Exception("Video generation timed out")

# 使い方
video = generate_video()
completed_video = wait_for_video(video.id)
print(f"Video ready: {completed_video.url}")

Webhook 連携

パフォーマンスを重視する場合は、ポーリングではなく Webhook の利用を推奨します。

Webhook エンドポイントのセットアップ

// Express.js の例
import express from 'express';
import crypto from 'crypto';

const app = express();
app.use(express.json());

app.post('/webhooks/sora', (req, res) => {
  // Webhook 署名の検証
  const signature = req.headers['x-openai-signature'];
  const payload = JSON.stringify(req.body);

  if (!verifySignature(payload, signature)) {
    return res.status(401).send('Invalid signature');
  }

  // Webhook の処理
  const { id, status, url, error } = req.body;

  if (status === 'completed') {
    console.log(`Video ${id} completed: ${url}`);
    // 動画のダウンロードと処理
    downloadVideo(url, id);
  } else if (status === 'failed') {
    console.error(`Video ${id} failed: ${error}`);
    // エラー処理
  }

  res.status(200).send('OK');
});

function verifySignature(payload, signature) {
  const secret = process.env.WEBHOOK_SECRET;
  const hmac = crypto.createHmac('sha256', secret);
  const digest = hmac.update(payload).digest('hex');
  return digest === signature;
}

動画のダウンロード

JavaScript(ダウンロード)

import fs from 'fs';
import https from 'https';

async function downloadVideo(url, filename) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(`./videos/${filename}.mp4`);

    https.get(url, (response) => {
      response.pipe(file);

      file.on('finish', () => {
        file.close();
        console.log(`Downloaded: ${filename}.mp4`);
        resolve();
      });
    }).on('error', (err) => {
      fs.unlink(`./videos/${filename}.mp4`, () => {});
      reject(err);
    });
  });
}

Python(ダウンロード)

import requests

def download_video(url, filename):
    response = requests.get(url, stream=True)
    response.raise_for_status()

    filepath = f"./videos/{filename}.mp4"

    with open(filepath, 'wb') as file:
        for chunk in response.iter_content(chunk_size=8192):
            file.write(chunk)

    print(f"Downloaded: {filename}.mp4")
    return filepath

Sora2 APIエラー処理:リトライロジックとベストプラクティス

よくあるエラーへの対応

async function robustGenerate(prompt, options = {}) {
  try {
    const video = await openai.videos.generate({
      model: "sora-2",
      prompt,
      ...options
    });
    return video;

  } catch (error) {
    switch (error.status) {
      case 400:
        console.error("Invalid request:", error.message);
        // コンテンツポリシー違反またはフォーマット不正の可能性
        break;

      case 401:
        console.error("Authentication failed");
        // API キーを確認
        break;

      case 429:
        console.error("Rate limit exceeded");
        // 指数バックオフで再試行
        return retryWithBackoff(prompt, options);

      case 500:
        console.error("Server error");
        // 遅延後に再試行
        break;

      default:
        console.error("Unknown error:", error);
    }
    throw error;
  }
}

指数バックオフのリトライ

async function retryWithBackoff(fn, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;

      const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
      console.log(`Retry ${i + 1}/${maxRetries} after ${delay}ms`);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}

// 使い方
const video = await retryWithBackoff(() =>
  openai.videos.generate({
    model: "sora-2",
    prompt: "Your prompt here"
  })
);

レート制限(Rate Limiting)

シンプルなレートリミッタの実装

class RateLimiter {
  constructor(requestsPerMinute) {
    this.requestsPerMinute = requestsPerMinute;
    this.queue = [];
    this.processing = false;
  }

  async add(fn) {
    return new Promise((resolve, reject) => {
      this.queue.push({ fn, resolve, reject });
      this.process();
    });
  }

  async process() {
    if (this.processing || this.queue.length === 0) return;

    this.processing = true;
    const { fn, resolve, reject } = this.queue.shift();

    try {
      const result = await fn();
      resolve(result);
    } catch (error) {
      reject(error);
    }

    // レートに応じて待機
    const delay = 60000 / this.requestsPerMinute;
    await new Promise(resolve => setTimeout(resolve, delay));

    this.processing = false;
    this.process();
  }
}

// 使い方
const limiter = new RateLimiter(20); // 1 分あたり 20 リクエスト

for (const prompt of prompts) {
  await limiter.add(() => openai.videos.generate({
    model: "sora-2",
    prompt
  }));
}

本番運用のベストプラクティス

1. 設定管理

// config.js
export const config = {
  openai: {
    apiKey: process.env.OPENAI_API_KEY,
    model: "sora-2",
    defaultDuration: 10,
    defaultResolution: "1080p",
    timeout: 600000 // 10 分
  },
  storage: {
    provider: "s3", // または "gcs", "azure"
    bucket: process.env.STORAGE_BUCKET,
    region: process.env.STORAGE_REGION
  },
  webhooks: {
    endpoint: process.env.WEBHOOK_URL,
    secret: process.env.WEBHOOK_SECRET
  },
  rateLimit: {
    requestsPerMinute: 20,
    maxConcurrent: 5
  }
};

2. ロギングとモニタリング

import winston from 'winston';

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: 'error.log', level: 'error' }),
    new winston.transports.File({ filename: 'combined.log' })
  ]
});

async function generateWithLogging(prompt, metadata = {}) {
  const startTime = Date.now();

  logger.info('Video generation started', {
    prompt: prompt.substring(0, 100),
    ...metadata
  });

  try {
    const video = await openai.videos.generate({
      model: "sora-2",
      prompt,
      metadata
    });

    const duration = Date.now() - startTime;
    logger.info('Video generation completed', {
      videoId: video.id,
      duration: `${duration}ms`,
      ...metadata
    });

    return video;
  } catch (error) {
    logger.error('Video generation failed', {
      error: error.message,
      prompt: prompt.substring(0, 100),
      ...metadata
    });
    throw error;
  }
}

3. データベース連携

// Prisma ORM を使用
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function createVideoRecord(userId, prompt, options) {
  // レコード作成
  const record = await prisma.video.create({
    data: {
      userId,
      prompt,
      status: 'pending',
      duration: options.duration,
      resolution: options.resolution,
      aspectRatio: options.aspect_ratio
    }
  });

  try {
    // 動画を生成
    const video = await openai.videos.generate({
      model: "sora-2",
      prompt,
      ...options,
      metadata: { recordId: record.id }
    });

    // 動画 ID で更新
    await prisma.video.update({
      where: { id: record.id },
      data: {
        videoId: video.id,
        status: 'processing'
      }
    });

    return record;
  } catch (error) {
    // 失敗時に状態・エラーを書き込み
    await prisma.video.update({
      where: { id: record.id },
      data: {
        status: 'failed',
        error: error.message
      }
    });
    throw error;
  }
}

Sora2 APIコード例:実際の統合シナリオ

例 1:バッチ動画ジェネレーター

class BatchVideoGenerator {
  constructor(openai, options = {}) {
    this.openai = openai;
    this.maxConcurrent = options.maxConcurrent || 5;
    this.onProgress = options.onProgress || (() => {});
    this.onComplete = options.onComplete || (() => {});
  }

  async generateBatch(prompts) {
    const results = [];
    const chunks = this.chunkArray(prompts, this.maxConcurrent);

    for (let i = 0; i < chunks.length; i++) {
      const chunk = chunks[i];
      const chunkResults = await Promise.all(
        chunk.map(prompt => this.generateSingle(prompt))
      );

      results.push(...chunkResults);
      this.onProgress({
        completed: results.length,
        total: prompts.length,
        percentage: (results.length / prompts.length) * 100
      });
    }

    this.onComplete(results);
    return results;
  }

  async generateSingle(prompt) {
    try {
      const video = await this.openai.videos.generate({
        model: "sora-2",
        prompt
      });

      const completed = await this.waitForVideo(video.id);
      return { success: true, prompt, video: completed };
    } catch (error) {
      return { success: false, prompt, error: error.message };
    }
  }

  chunkArray(array, size) {
    const chunks = [];
    for (let i = 0; i < array.length; i += size) {
      chunks.push(array.slice(i, i + size));
    }
    return chunks;
  }

  async waitForVideo(videoId) {
    // 前述の実装を再利用
  }
}

// 使い方
const generator = new BatchVideoGenerator(openai, {
  maxConcurrent: 3,
  onProgress: (progress) => {
    console.log(`Progress: ${progress.percentage.toFixed(1)}%`);
  }
});

const prompts = [
  "A cat playing with yarn",
  "Sunset over mountains",
  "Busy city street at night"
];

const results = await generator.generateBatch(prompts);

例 2:ソーシャルメディア用コンテンツ・パイプライン

class SocialMediaPipeline {
  async createCampaign(content, platforms) {
    const videos = {};

    for (const platform of platforms) {
      const config = this.getPlatformConfig(platform);
      const prompt = this.optimizePromptForPlatform(content, platform);

      const video = await openai.videos.generate({
        model: "sora-2",
        prompt,
        aspect_ratio: config.aspectRatio,
        duration: config.maxDuration
      });

      const completed = await waitForVideo(video.id);
      const downloaded = await downloadVideo(completed.url, `${platform}_${Date.now()}`);

      videos[platform] = {
        file: downloaded,
        url: completed.url,
        platform,
        config
      };
    }

    return videos;
  }

  getPlatformConfig(platform) {
    const configs = {
      youtube: { aspectRatio: "16:9", maxDuration: 60 },
      instagram: { aspectRatio: "1:1", maxDuration: 30 },
      tiktok: { aspectRatio: "9:16", maxDuration: 60 },
      twitter: { aspectRatio: "16:9", maxDuration: 30 }
    };
    return configs[platform];
  }

  optimizePromptForPlatform(content, platform) {
    const styles = {
      youtube: "cinematic, professional",
      instagram: "aesthetic, trendy, high saturation",
      tiktok: "energetic, fast-paced, engaging",
      twitter: "attention-grabbing, clear message"
    };

    return `${content}, ${styles[platform]}, optimized for ${platform}`;
  }
}

// 使い方
const pipeline = new SocialMediaPipeline();
const videos = await pipeline.createCampaign(
  "Product launch teaser for new smartphone",
  ["youtube", "instagram", "tiktok"]
);

セキュリティ上の考慮事項

1. API キーの保護

// ❌ やってはいけない例
const openai = new OpenAI({
  apiKey: "sk-..."  // ハードコードされたキー
});

// ✅ 環境変数を使用
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY
});

// ✅ 秘密情報管理サービスを使用
import { SecretsManager } from '@aws-sdk/client-secrets-manager';

async function getApiKey() {
  const client = new SecretsManager({ region: 'us-east-1' });
  const response = await client.getSecretValue({
    SecretId: 'openai-api-key'
  });
  return JSON.parse(response.SecretString).apiKey;
}

2. コンテンツフィルタリング

async function safeGenerate(prompt) {
  // 事前バリデーション
  if (!isValidPrompt(prompt)) {
    throw new Error("Invalid prompt content");
  }

  // コンテンツモデレーション
  const moderation = await openai.moderations.create({
    input: prompt
  });

  if (moderation.results[0].flagged) {
    throw new Error("Prompt violates content policy");
  }

  // 動画生成
  return await openai.videos.generate({
    model: "sora-2",
    prompt
  });
}

function isValidPrompt(prompt) {
  return prompt.length > 10 && prompt.length < 1000;
}

まとめ

本ガイドを通じて、Sora 2 API の全体像を理解できました。

✅ 認証とセットアップ ✅ 基本〜高度な生成パラメータ ✅ ポーリングと Webhook による非同期処理 ✅ エラー処理とリトライ ✅ レート制限と最適化 ✅ 本番環境でのベストプラクティス ✅ 実運用の統合例 ✅ セキュリティ上の注意点

次のステップ

  1. 開発環境で実験:API を試す
  2. 小さな PoC を構築:概念実証アプリを作る
  3. ユースケースに最適化:要件に合わせて調整
  4. 本番運用へ拡張:監視を整えスケール
  5. 最新情報を追う:API の変更や新機能をウォッチ

追加リソース


最終更新:October 2025 著者:Sora2Everything チーム 読了目安:18 分

関連チュートリアル

Sora 2プロンプトエンジニアリングの理解

より良いAI動画生成結果のための効果的なプロンプトの作成方法を学びます。

Sora 2での動画品質の最適化

動画品質を最大化し、生成時間を短縮するためのヒントとコツ。

Sora2 API完全ドキュメント|統合ガイドとコード例 2025