Python - 如何通过循环分页 API 来提取数据(收获)

Python - how to extract data by looping through paginated API (Harvest)


首先,我已经使用 Python 工作了大约几天,所以我不一定了解最佳实践或所有术语……但。我通过逆向工程学得最好,我下面的代码基于 Harvest 的官方文档和我在 google-fu

中找到的其他位

我的要求是从 Harvest 下载所有时间条目记录并保存为 JSON(或者最好是 CSV 文件)。

Official Python Example from Harvest Git Hub

这是我改编的代码(包括所有输出,在最终代码中不是必需的,但对我的学习很方便):

import requests, json, urllib.request

#Set variables for authorisation
AUTH = "REDACTED"
ACCOUNT = "REDACTED"

URL = "https://api.harvestapp.com/v2/time_entries"
HEADERS = { "Authorization": AUTH,
            "Harvest-Account-ID": ACCOUNT}
PAGENO = str("5")

request = urllib.request.Request(url=URL+"?page="+PAGENO, headers=HEADERS)
response = urllib.request.urlopen(request, timeout=5)
responseBody = response.read().decode("utf-8")
jsonResponse = json.loads(responseBody)

# Find the values for pagination
parsed = json.loads(responseBody)
links_first = parsed["links"]["first"]
links_last = parsed["links"]["last"]
links_next = parsed["links"]["next"]
links_previous = parsed["links"]["previous"]
nextpage = parsed["next_page"]
page = parsed["page"]
perpage = parsed["per_page"]
prevpage = parsed["previous_page"]
totalentries = parsed["total_entries"]
totalpages = parsed["total_pages"]

#Print the output
print(json.dumps(jsonResponse, sort_keys=True, indent=4))
print("first link : " + links_first)
print("last link : " + links_last)
print("next page : " + str(nextpage))
print("page : " + str(page))
print("per page : " + str(perpage))
print("total records : " + str(totalentries))
print("total pages : " + str(totalpages))

输出响应是
"Squeezed text (5816 lines)"
首先 link : https://api.harvestapp.com/v2/time_entries?page=1&per_page=100
最后 link : https://api.harvestapp.com/v2/time_entries?page=379&per_page=100
下一页:6
页数:5
每页 : 100
总记录数:37874
总页数:379

有人可以建议循环浏览页面以形成一个 JSON 文件的最佳方法吗? 如果您也能建议最好的方法然后输出那个 JSON 文件,我将不胜感激。

我一直在使用以下代码来检索所有时间条目。也许它可能更有效一点,但它确实有效。函数 get_all_time_entries 遍历所有页面并将 JSON 格式的响应附加到 all_time_entries 数组,最后 returns 这个数组。

import requests
import json

def get_all_time_entries():

    url_address = "https://api.harvestapp.com/v2/time_entries"  
    headers = {
        "Authorization": "Bearer " + "xxxxxxxxxx",
        "Harvest-Account-ID": "xxxxxx"
    }

    # find out total number of pages
    r = requests.get(url=url_address, headers=headers).json()
    total_pages = int(r['total_pages'])

    # results will be appended to this list
    all_time_entries = []

    # loop through all pages and return JSON object
    for page in range(1, total_pages):

        url = "https://api.harvestapp.com/v2/time_entries?page="+str(page)              
        response = requests.get(url=url, headers=headers).json()        
        all_time_entries.append(response)       
        page += 1

    # prettify JSON
    data = json.dumps(all_time_entries, sort_keys=True, indent=4)

    return data

print(get_all_time_entries())

你 运行 在 powershell 等 运行 时,可以轻松地将带有“>”的脚本输出定向到本地文件夹

例如:

Python.exe example.py > C:\temp\all_time_entries.json

希望对您有所帮助!

有一个 Python 库支持 Harvest API v2。

该库支持所有身份验证方法、请求速率限制、响应代码,并且每个响应对象都有数据类。

该库经过了很好的测试,因此您将在测试中获得每个端点的用法示例。测试使用官方 Harvest 示例。

另外还有一个继承Harvest对象的详细时间报告示例。详细时间报告的测试显示了如何使用它。

库引用自Harvest软件目录; https://www.getharvest.com/integrations/python-library

项目URL; https://github.com/bradbase/python-harvest_apiv2

我拥有该项目。


from harvest import Harvest
from .harvestdataclasses import *

class MyTimeEntries(Harvest):

    def __init__(self, uri, auth):
        super().__init__(uri, auth)


    def time_entries(self):
        time_entry_results = []
       
        time_entries = self.time_entries()
        time_entry_results.extend(time_entries.time_entries)
        if time_entries.total_pages > 1:
            for page in range(2, time_entries.total_pages + 1):
                time_entries = self.time_entries(page=page)
                time_entry_results.extend(time_entries.time_entries)
        
        return time_entry_results

personal_access_token = PersonalAccessToken('ACCOUNT_NUMBER', 'PERSONAL_ACCESS_TOKEN')
my_report = MyTimeEntries('https://api.harvestapp.com/api/v2', personal_access_token)
time_entries = my_report.time_entries()