Michael Brunner
Michael Brunner

Reputation: 11

Read JSON data from API to Python

I am trying to read from an API data on component setups. Basically the communication with the API works. However, I noticed that not all values I expect are loaded.

There should be 52 components (https://lignumdata.ch/?page=bauteil&bauteilgruppe=decke) in the list, but I get back only 13.

API = https://lignumdata.ch/api/

what am I doing wrong?

import json
import urllib.request
import urllib.parse
import urllib



def main():
    URL = 'https://lignumdata.ch/api/v1.cfc?method=getBauteil&compatMode=true&condition={"type":"decke","bauteiltyp":["Rippen", "Balken"]}'
    
request_url = URL.replace(" ", "")
    
    print('url', request_url)

    response = urllib.request.urlopen(request_url)
    data = json.loads(response.read()) 
    #print('url', data[0])

    for output_loads in data:
        print(output_loads['laufnummer'])
                
    return


if __name__ == '__main__':
    main()

Upvotes: 0

Views: 103

Answers (1)

Samy
Samy

Reputation: 649

The results are paginated. You need to pick a specific page with page={pagenum}. However, the API you provided mentioned this: If authenticated, the getBauteilIndex route now accepts page=all to turn off pagination.

I don't know if it's possible to turn pagination off for the method you used though, but even if it is possible, you will need to be authenticated.

EDIT:

Based on the comments, here's how to send an authenticated request:

import request
import base64

url = "http://example.com"

username = "user"    
password = "password"
authstr = username + ':' + password
asciistr = authstr.encode('ascii')
b64str = base64.b64encode(asciistr).decode()

headers = {
    'Authorization': "Basic " + b64str
    }

querystring = {"param1": "value", "param2": "value"}
response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

Upvotes: 1

Related Questions