threads-api

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Threads API Skill

Threads API 技能文档

Comprehensive assistance with Meta's Threads API development for building applications that integrate with the Threads social platform.
为构建与Threads社交平台集成的应用提供Meta Threads API开发的全面指导。

When to Use This Skill

何时使用此技能

This skill should be triggered when you are:
  • Building Threads integrations - Creating apps that post to or read from Threads
  • Implementing authentication - Setting up OAuth flows for Threads API access
  • Working with media uploads - Uploading images, videos, or carousel posts to Threads
  • Managing user content - Publishing, retrieving, or managing Threads posts
  • Fetching analytics - Retrieving insights and metrics for Threads content
  • Handling webhooks - Processing real-time updates from Threads
  • Troubleshooting API errors - Debugging authentication, rate limits, or API responses
  • Reading Threads profiles - Fetching user profile data and posts
当你遇到以下场景时,可使用此技能:
  • 构建Threads集成 - 创建可向Threads发布内容或从中读取内容的应用
  • 实现认证机制 - 搭建Threads API访问的OAuth流程
  • 处理媒体上传 - 向Threads上传图片、视频或轮播帖
  • 管理用户内容 - 发布、检索或管理Threads帖子
  • 获取分析数据 - 提取Threads内容的洞察与指标
  • 处理Webhook - 接收并处理来自Threads的实时更新
  • 排查API错误 - 调试认证、速率限制或API响应相关问题
  • 读取Threads资料 - 获取用户资料数据与帖子

Quick Reference

快速参考

Authentication - Getting an Access Token

认证 - 获取访问令牌

javascript
// Step 1: Redirect user to authorization endpoint
const authUrl = `https://threads.net/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&scope=threads_basic,threads_content_publish&response_type=code`;

// Step 2: Exchange authorization code for access token
const response = await fetch('https://graph.threads.net/oauth/access_token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: new URLSearchParams({
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    grant_type: 'authorization_code',
    redirect_uri: REDIRECT_URI,
    code: authorizationCode
  })
});

const { access_token } = await response.json();
javascript
// Step 1: Redirect user to authorization endpoint
const authUrl = `https://threads.net/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&scope=threads_basic,threads_content_publish&response_type=code`;

// Step 2: Exchange authorization code for access token
const response = await fetch('https://graph.threads.net/oauth/access_token', {
  method: 'POST',
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  body: new URLSearchParams({
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    grant_type: 'authorization_code',
    redirect_uri: REDIRECT_URI,
    code: authorizationCode
  })
});

const { access_token } = await response.json();

Publishing a Text Post

发布文字帖

javascript
// Create a simple text post
const response = await fetch(`https://graph.threads.net/v1.0/me/threads`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${accessToken}`
  },
  body: JSON.stringify({
    media_type: 'TEXT',
    text: 'Hello from Threads API! 🎉'
  })
});

const data = await response.json();
console.log('Post ID:', data.id);
javascript
// Create a simple text post
const response = await fetch(`https://graph.threads.net/v1.0/me/threads`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${accessToken}`
  },
  body: JSON.stringify({
    media_type: 'TEXT',
    text: 'Hello from Threads API! 🎉'
  })
});

const data = await response.json();
console.log('Post ID:', data.id);

Publishing an Image Post

发布图片帖

python
import requests
python
import requests

Upload and publish an image

Upload and publish an image

url = "https://graph.threads.net/v1.0/me/threads" headers = {"Authorization": f"Bearer {access_token}"}
data = { "media_type": "IMAGE", "image_url": "https://example.com/image.jpg", "text": "Check out this image! #API" }
response = requests.post(url, headers=headers, json=data) post_id = response.json()["id"] print(f"Posted image with ID: {post_id}")
undefined
url = "https://graph.threads.net/v1.0/me/threads" headers = {"Authorization": f"Bearer {access_token}"}
data = { "media_type": "IMAGE", "image_url": "https://example.com/image.jpg", "text": "Check out this image! #API" }
response = requests.post(url, headers=headers, json=data) post_id = response.json()["id"] print(f"Posted image with ID: {post_id}")
undefined

Publishing a Video Post

发布视频帖

javascript
// Step 1: Create a video container
const container = await fetch(`https://graph.threads.net/v1.0/me/threads`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${accessToken}` },
  body: JSON.stringify({
    media_type: 'VIDEO',
    video_url: 'https://example.com/video.mp4',
    text: 'Check out this video!'
  })
});

const { id: containerId } = await container.json();

// Step 2: Publish the container
await fetch(`https://graph.threads.net/v1.0/me/threads_publish`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${accessToken}` },
  body: JSON.stringify({ creation_id: containerId })
});
javascript
// Step 1: Create a video container
const container = await fetch(`https://graph.threads.net/v1.0/me/threads`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${accessToken}` },
  body: JSON.stringify({
    media_type: 'VIDEO',
    video_url: 'https://example.com/video.mp4',
    text: 'Check out this video!'
  })
});

const { id: containerId } = await container.json();

// Step 2: Publish the container
await fetch(`https://graph.threads.net/v1.0/me/threads_publish`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${accessToken}` },
  body: JSON.stringify({ creation_id: containerId })
});

Fetching User Profile

获取用户资料

python
import requests
python
import requests

Get authenticated user's profile

Get authenticated user's profile

url = f"https://graph.threads.net/v1.0/me" headers = {"Authorization": f"Bearer {access_token}"} params = { "fields": "id,username,name,threads_profile_picture_url,threads_biography" }
response = requests.get(url, headers=headers, params=params) profile = response.json()
print(f"Username: {profile['username']}") print(f"Bio: {profile['threads_biography']}")
undefined
url = f"https://graph.threads.net/v1.0/me" headers = {"Authorization": f"Bearer {access_token}"} params = { "fields": "id,username,name,threads_profile_picture_url,threads_biography" }
response = requests.get(url, headers=headers, params=params) profile = response.json()
print(f"Username: {profile['username']}") print(f"Bio: {profile['threads_biography']}")
undefined

Fetching User's Threads

获取用户的Threads帖子

javascript
// Get user's recent threads with pagination
const response = await fetch(
  `https://graph.threads.net/v1.0/me/threads?fields=id,text,timestamp,media_url&limit=25`,
  {
    headers: { 'Authorization': `Bearer ${accessToken}` }
  }
);

const { data, paging } = await response.json();
data.forEach(thread => {
  console.log(`${thread.timestamp}: ${thread.text}`);
});

// Use paging.next for next page
javascript
// Get user's recent threads with pagination
const response = await fetch(
  `https://graph.threads.net/v1.0/me/threads?fields=id,text,timestamp,media_url&limit=25`,
  {
    headers: { 'Authorization': `Bearer ${accessToken}` }
  }
);

const { data, paging } = await response.json();
data.forEach(thread => {
  console.log(`${thread.timestamp}: ${thread.text}`);
});

// Use paging.next for next page

Publishing a Carousel Post

发布轮播帖

python
import requests
python
import requests

Create a carousel with multiple images

Create a carousel with multiple images

url = "https://graph.threads.net/v1.0/me/threads" headers = {"Authorization": f"Bearer {access_token}"}
data = { "media_type": "CAROUSEL", "children": [ {"media_type": "IMAGE", "image_url": "https://example.com/img1.jpg"}, {"media_type": "IMAGE", "image_url": "https://example.com/img2.jpg"}, {"media_type": "IMAGE", "image_url": "https://example.com/img3.jpg"} ], "text": "Swipe through these images! 📸" }
response = requests.post(url, headers=headers, json=data) carousel_id = response.json()["id"]
undefined
url = "https://graph.threads.net/v1.0/me/threads" headers = {"Authorization": f"Bearer {access_token}"}
data = { "media_type": "CAROUSEL", "children": [ {"media_type": "IMAGE", "image_url": "https://example.com/img1.jpg"}, {"media_type": "IMAGE", "image_url": "https://example.com/img2.jpg"}, {"media_type": "IMAGE", "image_url": "https://example.com/img3.jpg"} ], "text": "Swipe through these images! 📸" }
response = requests.post(url, headers=headers, json=data) carousel_id = response.json()["id"]
undefined

Retrieving Insights (Analytics)

获取洞察数据(分析)

javascript
// Get insights for a specific thread
const threadId = '123456789';
const response = await fetch(
  `https://graph.threads.net/v1.0/${threadId}/insights?metric=views,likes,replies,reposts`,
  {
    headers: { 'Authorization': `Bearer ${accessToken}` }
  }
);

const { data } = await response.json();
data.forEach(metric => {
  console.log(`${metric.name}: ${metric.values[0].value}`);
});
javascript
// Get insights for a specific thread
const threadId = '123456789';
const response = await fetch(
  `https://graph.threads.net/v1.0/${threadId}/insights?metric=views,likes,replies,reposts`,
  {
    headers: { 'Authorization': `Bearer ${accessToken}` }
  }
);

const { data } = await response.json();
data.forEach(metric => {
  console.log(`${metric.name}: ${metric.values[0].value}`);
});

Error Handling Pattern

错误处理模式

python
import requests

def make_threads_request(url, access_token, method='GET', **kwargs):
    """Robust error handling for Threads API requests"""
    headers = kwargs.pop('headers', {})
    headers['Authorization'] = f"Bearer {access_token}"

    try:
        response = requests.request(method, url, headers=headers, **kwargs)
        response.raise_for_status()
        return response.json()

    except requests.exceptions.HTTPError as e:
        error_data = e.response.json()
        error_code = error_data.get('error', {}).get('code')
        error_msg = error_data.get('error', {}).get('message')

        if error_code == 190:
            raise Exception(f"Invalid access token: {error_msg}")
        elif error_code == 32:
            raise Exception(f"Rate limit exceeded: {error_msg}")
        else:
            raise Exception(f"API Error {error_code}: {error_msg}")

    except requests.exceptions.RequestException as e:
        raise Exception(f"Network error: {str(e)}")
python
import requests

def make_threads_request(url, access_token, method='GET', **kwargs):
    """Robust error handling for Threads API requests"""
    headers = kwargs.pop('headers', {})
    headers['Authorization'] = f"Bearer {access_token}"

    try:
        response = requests.request(method, url, headers=headers, **kwargs)
        response.raise_for_status()
        return response.json()

    except requests.exceptions.HTTPError as e:
        error_data = e.response.json()
        error_code = error_data.get('error', {}).get('code')
        error_msg = error_data.get('error', {}).get('message')

        if error_code == 190:
            raise Exception(f"Invalid access token: {error_msg}")
        elif error_code == 32:
            raise Exception(f"Rate limit exceeded: {error_msg}")
        else:
            raise Exception(f"API Error {error_code}: {error_msg}")

    except requests.exceptions.RequestException as e:
        raise Exception(f"Network error: {str(e)}")

Key Concepts

核心概念

Access Tokens and Permissions

访问令牌与权限

  • Access Tokens: OAuth 2.0 tokens required for all API requests
  • Scopes: Define what your app can access (e.g.,
    threads_basic
    ,
    threads_content_publish
    ,
    threads_manage_insights
    )
  • Token Expiration: Long-lived tokens (60 days) and refresh tokens for extended access
  • Access Tokens:所有API请求都需要的OAuth 2.0令牌
  • Scopes:定义应用可访问的权限范围(例如:
    threads_basic
    threads_content_publish
    threads_manage_insights
  • Token Expiration:长效令牌(60天)和刷新令牌,用于延长访问权限

Media Types

媒体类型

  • TEXT: Simple text posts
  • IMAGE: Single image with optional caption
  • VIDEO: Single video with optional caption
  • CAROUSEL: Multiple images or videos in a swipeable format
  • TEXT:纯文字帖子
  • IMAGE:带可选说明的单张图片
  • VIDEO:带可选说明的单个视频
  • CAROUSEL:可滑动浏览的多张图片或视频

Publishing Flow

发布流程

  1. Container Creation: Create a media container with content
  2. Publishing: Publish the container to make it visible
  3. Two-stage process: Required for videos and carousels to allow processing time
  1. 容器创建:创建包含内容的媒体容器
  2. 发布操作:发布容器使其可见
  3. 两步流程:视频和轮播帖需要此流程,以留出处理时间

Rate Limits

速率限制

  • Rate limits vary by endpoint and access level
  • Standard rate limit: 200 calls per hour per user
  • Monitor
    X-Business-Use-Case-Usage
    header in responses
  • Implement exponential backoff for rate limit errors
  • 不同端点和访问级别有不同的速率限制
  • 标准速率限制:每用户每小时200次调用
  • 监控响应头中的
    X-Business-Use-Case-Usage
    字段
  • 遇到速率限制错误时,实现指数退避策略

Webhooks

Webhook

  • Real-time notifications for events like mentions, replies, or new followers
  • Requires HTTPS endpoint for receiving notifications
  • Must validate webhook signatures for security
  • 用于接收提及、回复或新关注者等事件的实时通知
  • 需要HTTPS端点来接收通知
  • 必须验证Webhook签名以保障安全

Reference Files

参考文件

This skill includes comprehensive documentation in
references/
:
  • other.md - Complete Threads API documentation including:
    • Authentication and authorization flows
    • API endpoints reference
    • Request/response formats
    • Error codes and troubleshooting
    • Best practices and guidelines
Use the skill's reference files when you need detailed information about specific API endpoints, parameters, or advanced features.
此技能在
references/
目录下包含全面的文档:
  • other.md - 完整的Threads API文档,包括:
    • 认证与授权流程
    • API端点参考
    • 请求/响应格式
    • 错误代码与故障排查
    • 最佳实践与指南
当你需要了解特定API端点、参数或高级功能的详细信息时,请使用技能的参考文件。

Working with This Skill

使用此技能的指南

For Beginners

初学者

Start by understanding the authentication flow - this is the foundation of all Threads API integrations. Focus on:
  1. Setting up your Meta developer account and app
  2. Implementing OAuth 2.0 authorization
  3. Making your first API request to fetch user profile
  4. Publishing a simple text post
从理解认证流程开始——这是所有Threads API集成的基础。重点关注:
  1. 设置Meta开发者账户与应用
  2. 实现OAuth 2.0授权
  3. 发起首个API请求以获取用户资料
  4. 发布简单的文字帖

For Intermediate Users

中级用户

Build on the basics by exploring:
  1. Media uploads (images and videos)
  2. Carousel posts for multi-image content
  3. Webhook integration for real-time updates
  4. Error handling and retry logic
  5. Rate limit management
在基础之上探索以下内容:
  1. 媒体上传(图片与视频)
  2. 多图内容的轮播帖
  3. Webhook集成以接收实时更新
  4. 错误处理与重试逻辑
  5. 速率限制管理

For Advanced Users

高级用户

Optimize your integration with:
  1. Insights and analytics data
  2. Batch operations for efficiency
  3. Advanced content scheduling
  4. Custom webhook event processing
  5. Multi-account management
通过以下方式优化集成:
  1. 洞察与分析数据
  2. 批量操作提升效率
  3. 高级内容调度
  4. 自定义Webhook事件处理
  5. 多账户管理

Navigation Tips

导航提示

  • Quick Reference: Use the code examples above for common tasks
  • Reference Files: Dive into
    references/other.md
    for complete API documentation
  • Authentication First: Always start with proper authentication setup
  • Test in Sandbox: Use Meta's test users and sandbox environment during development
  • 快速参考:使用上述代码示例完成常见任务
  • 参考文件:深入阅读
    references/other.md
    获取完整API文档
  • 先做认证:始终从正确的认证设置开始
  • 沙箱测试:开发期间使用Meta的测试用户与沙箱环境

Common Workflows

常见工作流

Complete Post Publishing Flow

完整帖子发布流程

  1. Obtain access token via OAuth flow
  2. Create media container (if using images/videos)
  3. Wait for container processing (for videos)
  4. Publish the container
  5. Retrieve post ID and insights
  1. 通过OAuth流程获取访问令牌
  2. 创建媒体容器(若使用图片/视频)
  3. 等待容器处理(针对视频)
  4. 发布容器
  5. 检索帖子ID与洞察数据

User Data Retrieval Flow

用户数据获取流程

  1. Authenticate user
  2. Fetch user profile with required fields
  3. Retrieve user's threads with pagination
  4. Process and display content
  1. 用户认证
  2. 获取包含所需字段的用户资料
  3. 分页检索用户的Threads帖子
  4. 处理并展示内容

Webhook Integration Flow

Webhook集成流程

  1. Set up HTTPS endpoint
  2. Register webhook subscription
  3. Validate webhook signatures
  4. Process incoming events
  5. Respond with 200 OK status
  1. 设置HTTPS端点
  2. 注册Webhook订阅
  3. 验证Webhook签名
  4. 处理传入事件
  5. 返回200 OK状态码

Best Practices

最佳实践

  1. Security
    • Never expose access tokens in client-side code
    • Always validate webhook signatures
    • Use environment variables for sensitive data
    • Implement token refresh before expiration
  2. Performance
    • Cache API responses when appropriate
    • Use batch requests for multiple operations
    • Implement pagination for large result sets
    • Monitor and respect rate limits
  3. User Experience
    • Provide clear error messages to users
    • Show loading states during API calls
    • Handle network failures gracefully
    • Request only necessary permissions
  4. Content Publishing
    • Validate media URLs before uploading
    • Check media format requirements
    • Add appropriate error handling for failed uploads
    • Consider using alt text for accessibility
  1. 安全
    • 切勿在客户端代码中暴露访问令牌
    • 始终验证Webhook签名
    • 使用环境变量存储敏感数据
    • 在令牌过期前实现刷新机制
  2. 性能
    • 适当缓存API响应
    • 使用批量请求处理多个操作
    • 对大型结果集实现分页
    • 监控并遵守速率限制
  3. 用户体验
    • 向用户提供清晰的错误提示
    • API调用期间显示加载状态
    • 优雅处理网络故障
    • 仅请求必要的权限
  4. 内容发布
    • 上传前验证媒体URL的可访问性
    • 检查媒体格式要求
    • 为上传失败添加适当的错误处理
    • 考虑为媒体添加替代文本以提升可访问性

Resources

资源

Official Documentation

官方文档

Developer Tools

开发者工具

  • Meta App Dashboard: Configure your app and manage permissions
  • Graph API Explorer: Test API calls interactively
  • Webhook Testing: Test webhook endpoints before production
  • Meta应用控制台:配置应用并管理权限
  • Graph API Explorer:交互式测试API调用
  • Webhook测试:上线前测试Webhook端点

Troubleshooting

故障排查

Common Issues

常见问题

Authentication Errors (Code 190)
  • Check access token validity
  • Verify token hasn't expired
  • Ensure correct permissions/scopes
Rate Limit Errors (Code 32)
  • Implement exponential backoff
  • Monitor API usage
  • Consider caching responses
Media Upload Failures
  • Verify media URL is publicly accessible
  • Check file format and size requirements
  • Ensure proper media_type parameter
Webhook Not Receiving Events
  • Verify endpoint is HTTPS
  • Check webhook signature validation
  • Ensure endpoint responds with 200 OK quickly
认证错误(代码190)
  • 检查访问令牌的有效性
  • 确认令牌未过期
  • 确保权限/范围正确
速率限制错误(代码32)
  • 实现指数退避策略
  • 监控API使用情况
  • 考虑缓存响应
媒体上传失败
  • 验证媒体URL是否可公开访问
  • 检查文件格式与大小要求
  • 确保
    media_type
    参数正确
Webhook未接收事件
  • 验证端点是否为HTTPS
  • 检查Webhook签名验证设置
  • 确保端点能快速返回200 OK

Notes

说明

  • This skill was generated from Meta's official Threads API documentation
  • The Threads API is part of Meta's Graph API family
  • API features and endpoints may be updated by Meta - refer to official docs for latest changes
  • Some features may require additional app review or permissions from Meta
  • 本技能基于Meta官方Threads API文档生成
  • Threads API属于Meta Graph API家族
  • API功能与端点可能由Meta更新,请参考官方文档获取最新信息
  • 部分功能可能需要Meta额外的应用审核或权限

Updating

更新方法

To refresh this skill with updated documentation:
  1. Visit https://developers.facebook.com/docs/threads for the latest information
  2. Re-run the documentation scraper with updated configuration
  3. The skill will be rebuilt with current API information
如需使用最新文档刷新此技能:
  1. 访问https://developers.facebook.com/docs/threads获取最新信息
  2. 使用更新后的配置重新运行文档抓取工具
  3. 技能将基于当前API信息重建