You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python通过Instagram API上传本地视频作为REEL?

解决Instagram API上传本地视频为Reel的问题

你当前的代码仅支持上传公网URL视频,本地视频上传需要调整请求格式和流程,以下是完整的解决方案:

核心问题说明

Instagram API上传本地视频时,不能使用video_url参数,必须通过**multipart/form-data格式上传文件**,并且需要等待Instagram完成视频转码后才能发布,这是和公网URL上传的核心区别。

修正后的完整代码

import requests
import json
import time

token = "..."
api_version = "v23.0"
headers = {
    "Authorization": f"Bearer {token}"
}

# 获取用户ID
id_url = f"https://graph.instagram.com/{api_version}/me"
id_response = requests.get(id_url, headers=headers)
user_id = id_response.json()['id']

# 1. 上传本地视频到Instagram媒体容器
upload_url = f"https://graph.instagram.com/{api_version}/{user_id}/media"
local_video_path = "/path/to/your/local/video.mp4"

# 注意:上传文件时不要手动设置Content-Type,requests会自动处理multipart/form-data格式
files = {
    'file': open(local_video_path, 'rb')
}
payload = {
    "media_type": "REELS",
    "caption": "我的本地视频Reel"  # 可选:添加Reel字幕
}

upload_response = requests.post(
    url=upload_url,
    headers=headers,
    files=files,
    data=payload
)
media_id = upload_response.json()['id']
print(f"媒体上传成功,ID: {media_id}")

# 2. 轮询等待视频转码完成(必须步骤)
def wait_for_media_processing(media_id):
    status_url = f"https://graph.instagram.com/{api_version}/{media_id}?fields=status_code"
    while True:
        status_response = requests.get(status_url, headers=headers)
        status_data = status_response.json()
        status = status_data.get('status_code')
        if status == "FINISHED":
            print("视频转码完成")
            return True
        elif status == "FAILED":
            print("视频转码失败,请检查视频格式")
            return False
        print(f"当前转码状态: {status},5秒后重试...")
        time.sleep(5)

wait_for_media_processing(media_id)

# 3. 发布Reel
publish_url = f"https://graph.instagram.com/{api_version}/{user_id}/media_publish"
publish_payload = {
    "creation_id": media_id
}
publish_response = requests.post(publish_url, headers=headers, data=publish_payload)
reel_id = publish_response.json()['id']
print(f"Reel发布成功,ID: {reel_id}")

关键调整点

  1. 请求格式修改:移除了Content-Type: application/json请求头,改用files参数传递本地视频文件,requests会自动生成正确的multipart/form-data格式。
  2. 新增转码等待逻辑:本地视频上传后,Instagram需要时间转码,必须轮询直到status_code变为FINISHED才能发布,否则会失败。
  3. 修复原代码错误:修正了video_path未定义、out.content引用错误、末尾多余括号等问题。

常见排查方向

  • 权限验证:确保你的access_token拥有instagram_content_publish和instagram_basic权限,可通过debug_token端点检查权限列表。
  • 视频规格检查:必须符合Reel要求:MP4格式、H.264编码、AAC音频、时长15-90秒、文件大小≤4GB、分辨率建议1080x1920(竖屏)。
  • 应用状态:如果是公开应用,需通过Facebook应用审核获取instagram_content_publish权限;测试阶段可添加测试用户绕过审核。
  • 网络环境:确保服务器能正常访问Instagram API端点,无防火墙或代理限制。

内容的提问来源于stack exchange,提问作者Physics_Student

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 12:55:56