如何解析 Youtube 构建 API 查询(python 烧瓶)的响应 Header

How To Parse the Response Header of a Youtube Build API Query (python flask)

我正在通过以下方式致电 YouTube API:

youtube = build(
    'youtube', 'v3',
    developerKey=API_KEY)

videoList = youtube.playlistItems().list(
    part="id, contentDetails, snippet, status", 
    maxResults=50,
    playlistId=PLAYLIST_ID
).execute()

return videoList

哪个 returns 我可以解析的项目字典。

但我正在尝试解析响应 header,以便我可以提取 nextPageToken 以获取下一页... 但是找不到任何关于如何使用上述方法提取它的信息。

非常感谢任何提示

首先要注意的是,要传递给 PlaylistItems.list API 端点的下一次调用的页面令牌不会在 HTTP 响应中找到 header 产生于前一个 API 调用。

根据 PlaylistItems.list 端点的官方文档,调用端点的 JSON response obtained 看起来像:

{
  "kind": "youtube#playlistItemListResponse",
  "etag": etag,
  "nextPageToken": string,
  "prevPageToken": string,
  "pageInfo": {
    "totalResults": integer,
    "resultsPerPage": integer
  },
  "items": [
    playlistItem Resource
  ]
}

现在,很明显,您需要实现的页面令牌 API result set pagination is available within the endpoint response itself -- not within the HTTP response header (which is another thing) -- as value of the property nextPageToken

但是,从 Google 的 API 的 Python 客户端库的用户的角度来看(从显示的源代码推断),API 结果集分页看起来更 pythonic (即您不需要显式使用 nextPageToken):

request = youtube.playlistItems().list(
    part = 'id,contentDetails,snippet,status',
    playlistId = PLAYLIST_ID,
    maxResults = 50
)
playlistItems = []

while request:
    response = request.execute()
    playlistItems.extend(response['items'])
    request = youtube.playlistItems().list_next(
        request, response)

return playlistItems

请注意,此代码并非 return videos,而是故意 playlistItems。 JSON object 在调用 request.execute() 时产生的结果不是 video resource,而是上面引用的 PlaylistItems.list 响应 object。

后者 object 的内部 items 数组包含与 PLAYLIST_ID 标识的播放列表中包含的条目相关的所有元数据;这些条目是 PlaylistItems resource objects。上面的代码使用 playlistItems.extend 仅将 object 添加到 playlistItems 引用相应播放列表的项目。


Google 的 APIs 客户端库的文档 Python

记录客户端库的主要站点是:Google API Client Library for Python Docs. Its source is public, to be found within the client library's public repo under the directory docs

分页也有说明,在页面 How to... Use Pagination.

同样有趣的是也看到了 YouTube Data API's list of all instance methods. Your method of interest -- playlistItems.list_next -- is documented