instagram-private-api 中 TopicalExploreFeedResponseCandidatesItem 接口详解:Instagram 话题探索流图片候选响应结构

原创2026-10-15 17:51:341,407 阅读
文章标签:后端

instagram-private-api 中 TopicalExploreFeedResponseCandidatesItem 接口详解:Instagram 话题探索流图片候选响应结构

本篇聚焦 instagram-private-api 的响应类型 TopicalExploreFeedResponseCandidatesItem,它定义了 Instagram 话题探索流(Topical Explore Feed)中每条媒体 image_versions2.candidates 数组项的结构。读完后你将理解该接口在整个响应数据流中的位置、五个字段的含义与可空性差异,并知道如何通过 TopicalExploreFeed 请求数据、按分辨率挑选可用的图片 URL。

接口定位:它在响应树中的位置

TopicalExploreFeedResponseCandidatesItem 定义在 src/responses/topical-explore.feed.response.ts,完整的接口定义如下(与 docs/interfaces/responses/TopicalExploreFeedResponseCandidatesItem.md 文档一一对应):

export interface TopicalExploreFeedResponseCandidatesItem {
    width: number;
    height: number;
    url: string;
    scans_profile?: string;
    estimated_scans_sizes?: number[];
}

它并非顶层接口,而是嵌套在探索流响应树的深层位置。沿着同文件的类型引用关系自上而下展开,数据流路径为:

TopicalExploreFeedResponseRootObject
└── sectional_items: TopicalExploreFeedResponseSectionalItemsItem[]
    └── layout_content: TopicalExploreFeedResponseLayout_content
        ├── medias?: TopicalExploreFeedResponseMediasItem[]        // 单列媒体列表
        ├── fill_items?: TopicalExploreFeedResponseFillItemsItem[] // 补位媒体
        └── two_by_two_item?                                      // 2x2 频道/IGTV 卡片
            └── media: TopicalExploreFeedResponseMedia
                └── image_versions2?: TopicalExploreFeedResponseImage_versions2
                    └── candidates: TopicalExploreFeedResponseCandidatesItem[]   // ← 本接口

其中 TopicalExploreFeedResponseImage_versions2(见 src/responses/topical-explore.feed.response.ts)的结构是 candidates 数组加一个可选的 additional_candidates(含 igtv_first_frame 与 first_frame 视频首帧)。也就是说:每当 Instagram 服务端返回一张媒体图片时,通常会附带多档缩略图 URL,candidates 数组中的每一项就是一个 TopicalExploreFeedResponseCandidatesItem,代表同一张图片的一个可用尺寸版本。

逐字段解析

文档中标注的五个字段及定义行号如下:

字段 类型 可空性 定义位置
width number 必填 topical-explore.feed.response.ts#L141
height number 必填 topical-explore.feed.response.ts#L142
url string 必填 topical-explore.feed.response.ts#L143
scans_profile string 可选 topical-explore.feed.response.ts#L144
estimated_scans_sizes number] 可选 [topical-explore.feed.response.ts#L145

与其他 Feed 的 candidates 结构对比

同一个 SDK 中还有多个同名的 *CandidatesItem 接口,对比它们能看出 TopicalExploreFeedResponseCandidatesItem 是字段最全的版本:

接口 定义位置 字段
UserFeedResponseCandidatesItem src/responses/user.feed.response.ts#L59-L63 width、height、url
LocationFeedResponseCandidatesItem src/responses/location.feed.response.ts#L117-L121 width、height、url
TopicalExploreFeedResponseCandidatesItem src/responses/topical-explore.feed.response.ts#L140-L146 width、height、url、scans_profile?、estimated_scans_sizes?

用户主页流(UserFeed)与地点流(LocationFeed)的候选项只保留了三要素,而话题探索流额外携带了两个可选的扫描配置字段。从源码结构看,这反映了不同接口在 Instagram 服务端返回体上的实际差异,也提醒开发者:处理 candidates 时不能假设各 feed 的候选项结构完全一致。

数据来源:TopicalExploreFeed 请求链

该接口的数据由 src/feeds/topical-explore.feed.ts 中的 TopicalExploreFeed 类产生(完整 API 文档见 docs/classes/feeds/TopicalExploreFeed.md)。关键实现点:

export class TopicalExploreFeed extends Feed<TopicalExploreFeedResponseRootObject, TopicalExploreFeedResponseSectionalItemsItem> {
  module: IgAppModule = 'explore_popular';
  lat?: string | number;
  lng?: string | number;
  /**
   * Change this to set the category
   */
  clusterId = 'explore_all:0';
  sessionId = chance.guid({ version: 4 });

  @Expose()
  private nextMaxId: string;

  set state(body: TopicalExploreFeedResponseRootObject) {
    this.nextMaxId = body.next_max_id;
    this.moreAvailable = body.more_available;
  }

  async items(): Promise<TopicalExploreFeedResponseSectionalItemsItem[]> {
    const res = await this.request();
    return res.sectional_items;
  }

  async request(): Promise<TopicalExploreFeedResponseRootObject> {
    const { body } = await this.client.request.send({
      url: '/api/v1/discover/topical_explore/',
      method: 'GET',
      qs: {
        is_prefetch: false,
        omit_cover_media: true,
        max_id: this.nextMaxId,
        module: this.module,
        reels_configuration: 'hide_hero',
        use_sectional_payload: true,
        timezone_offset: this.client.state.timezoneOffset,
        lat: this.lat,
        lng: this.lng,
        cluster_id: this.clusterId,
        session_id: this.sessionId,
        include_fixed_destinations: true,
      },
    });
    return body;
  }
}

要点说明:

  • 端点:GET /api/v1/discover/topical_explore/,对应 Instagram 客户端"探索"页的话题(topic)流。
  • cluster_id:默认 'explore_all:0',源码注释明确提示"Change this to set the category",即通过它切换话题分类。
  • session_id:默认由 chance.guid({ version: 4 }) 生成的 v4 UUID,标识一次探索会话;翻页请求间保持稳定。
  • lat / lng:可选经纬度,用于把探索结果偏向指定地理位置。
  • 分页:state setter 从响应根对象的 next_max_id / more_available 提取翻页游标;items() 返回的 sectional_items 即前面结构树的第二层,候选图片就藏在其中每个 section 的 media.image_versions2.candidates 里。

Feed 通过工厂方法创建,src/core/feed.factory.ts 中的 topicalExplore() 允许注入 sessionId、clusterId、lat、lng、module 五个可覆盖项:

public topicalExplore(
  options: Partial<Pick<TopicalExploreFeed, 'sessionId' | 'clusterId' | 'lat' | 'lng' | 'module'>> = {},
): TopicalExploreFeed {
  return plainToClassFromExist(new TopicalExploreFeed(this.client), options);
}

实战:获取探索流并挑选图片候选

结合上述实现,一个完整的调用示例如下(前提是客户端已完成登录,参见 README.md 的登录相关说明):

import { IgApiClient } from 'instagram-private-api';

const client = new IgApiClient();
// client.account.login({...}).then(...) 之后:

const feed = client.feed.topicalExplore({
  clusterId: 'explore_all:0',   // 话题分类,默认值
  module: 'explore_popular',    // 模块标识,默认值
  lat: '31.2304',               // 可选:纬度
  lng: '121.4737',              // 可选:经度
});

const sections = await feed.items();
for (const section of sections) {
  const media = section.layout_content.medias?.[0]?.media;
  const candidates = media?.image_versions2?.candidates;
  if (!candidates) continue;

  // 按目标分辨率挑选候选项;找不到精确档位时退而选最接近的
  const target = 1080;
  const best =
    candidates.find(c => c.height === target) ??
    candidates.reduce((a, b) =>
      Math.abs(a.height - target) < Math.abs(b.height - target) ? a : b);
  console.log(best.url, `${best.width}x${best.height}`);
}

几个与类型定义对应的注意事项:

  1. layout_content.medias、media.image_versions2、image_versions2.candidates 的每一项在接口中都带有可选性差异(medias?、image_versions2?),取值前需要做空值防护,上文示例中的可选链是必要的。
  2. candidates 本身在 TopicalExploreFeedResponseImage_versions2 中是必填数组,但可能只包含少数几档尺寸,"按高度精确匹配"应始终配合兜底策略。
  3. 若需要持续拉取多页数据,TopicalExploreFeed 继承自 src/core/feed.ts 的 Feed 基类,可直接使用 items$ / observable() 获得一个 RxJS Observable:基类内置了 do...while (this.isMoreAvailable()) 循环与 @lifeomic/attempt 指数退避重试(默认 maxAttempts: 10,对 400/429/500/502 状态码等待重试),翻页时会自动携带上一次 next_max_id 作为 max_id 参数。

小结与延伸阅读

TopicalExploreFeedResponseCandidatesItem 是探索流响应中"图片多尺寸候选"的最小单元:width / height / url 三要素保证任何一张媒体图都能被按档取用,scans_profile? / estimated_scans_sizes? 两个可选字段则忠实记录了 Instagram 服务端在探索流场景下额外返回的扫描配置元数据。它本身不含任何 SDK 逻辑,价值在于作为类型契约——让 TypeScript 调用方在解析 /api/v1/discover/topical_explore/ 响应时获得完整的编译期类型支持。

继续深入可参考:

登录后查看全文
instagram-private-api