简体   繁体   English

Python JSON 多个 API 请求

[英]Python JSON multiple API requests

I am trying to make multiple requests to an API and compile all the responses and convert the data to a dataframe.我正在尝试向 API 发出多个请求并编译所有响应并将数据转换为 dataframe。 I am having trouble with creating the dataframe with the JSON filesalthough it does gather the data I need.我在使用 JSON 文件创建 dataframe 时遇到问题,尽管它确实收集了我需要的数据。 I am left with an empty dataframe.我只剩下一个空的 dataframe。 If I remove the df.append I get the last request in the format I would like.如果我删除 df.append 我会得到我想要的格式的最后一个请求。 Any help would be greatly appreciated.任何帮助将不胜感激。 I have never worked with an API.我从未使用过 API。

import http.client, urllib.request, urllib.parse, urllib.error, base64

ID = ['H-IE0000750506','H-IE0000007080','H-IE0001665294']
df1 = pd.DataFrame()


headers = {'Ocp-Apim-Subscription-Key': 'XXXXXXXXXXXXXXXX'}

for x in ID:

    params = urllib.parse.urlencode({'paramX': x,})

    try:
        conn =http.client.HTTPSConnection('api.someAPI.com')
        conn.request('GET','/Company/Get?%s' % params, '{body}',headers)
        response = conn.getresponse()
        data = response.read()
        data = json.loads(data)
        df = pd.json_normalize(data['Result'])
        df1 = pd.append(df1,df)
        conn.close()
    except Exception as e:
        print('[Errno{0}] {1}'.format(e.errno, e.strerror))
for x in ID:

    params = urllib.parse.urlencode({
    
        'HitHorizonsId': x,
    })

    try:
        conn = http.client.HTTPSConnection('api.hithorizons.com')
        conn.request('GET','/Company/Get?%s' % params, '{body}', headers)
        response = conn.getresponse()
        data = response.read()
        data = json.loads(data)
        df = pd.json_normalize(data['Result'])
    except Exception as e:
        print('error')
    df1 = pd.concat([df1,df])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM