如何使用 CURL 从 Okta api 调用获取下一页

问题描述 投票:0回答:3

我目前正在向 Okta 查询事件列表。结果集有数万个。目前,请求限制返回 1000 个结果。根据 Okta API。 http://developer.okta.com/docs/getting_started/design_principles.html#pagination 我可以使用值为“next”的 Link 标头。

如何使用 CURL 捕获该值并在该 url 上发出 CURL 命令以获取其余值并循环直到结束?

api pagination okta
3个回答
3
投票

在 cURL 中,如果包含“-i”选项,标头将返回到控制台。在这些标题中,您将找到一个名为 rel="next" 的链接。如果您使用此过滤器替换第一个 GET 调用中的资源,您将获得下一组结果。


0
投票

分页代码基于 https://michaelheap.com/follow-github-link-header-bash

#!/usr/bin/env bash

# Set these:
url="https://COMPANY.okta.com/api/v1/users"
token="..."

# Pagination code based on https://michaelheap.com/follow-github-link-header-bash
while [ "$url" ]; do
    r=$(curl --compressed -Ss -i -H "authorization: SSWS $token" "$url" | tr -d '\r')
    echo "$r" | sed '1,/^$/d' | jq -r '.[].profile.login'
    url=$(echo "$r" | sed -n -E 's/link: <(.*)>; rel="next"/\1/pi')
done

请注意,如果您发出多个请求(您可能会这样做,因为您正在分页),那么使用 Python 之类的语言和

requests
包比curl 快得多。 requests
session
将使连接保持打开状态,而curl 会关闭它并每次重新打开它。

#!/usr/bin/env python

import requests

# Set these:
url = 'https://COMPANY.okta.com/api/v1/users'
token = '...'

# If you're making multiple API calls, using a session is much faster.
session = requests.Session()
session.headers['authorization'] = 'SSWS ' + token

def get_objects(url):
    while url:
        r = session.get(url)
        for o in r.json():
            yield o
        url = r.links.get('next', {}).get('url')
        
for user in get_objects(url):
    print(user['profile']['login'])

0
投票

此版本的 shell 脚本具有更好的变量名称,使其更易于理解。

与其他评论一样,使用

curl
-i
选项运行
--include
会包含响应标头。

#!/usr/bin/env bash

# Set these:
url='https://COMPANY.okta.com/api/v1/users'
token='...'

# Pagination code based on https://michaelheap.com/follow-github-link-header-bash
while [ "$url" ]; do
    r=$(curl --compressed -isSH "authorization: SSWS $token" "$url" | tr -d '\r')
    headers=$(echo "$r" | sed '/^$/q')
    body=$(echo "$r" | sed '1,/^$/d')
    echo "$body" | jq -r '.[].profile.login'
    url=$(echo "$headers" | sed -n -E 's/link: <(.*)>; rel="next"/\1/pi')
done
© www.soinside.com 2019 - 2024. All rights reserved.