Created
March 11, 2020 23:57
-
-
Save DuaneR5280/6abae298f33440471e26cb90f7a0fc72 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from requests_html import HTMLSession | |
import json | |
session = HTMLSession() | |
server_ip = '' # input server ip address. Add port if necessary | |
endpoints = { | |
"children": f"http://{server_ip}/api/children/", | |
"changes": f"http://{server_ip}/api/changes/", | |
"feedings": f"http://{server_ip}/api/feedings/", | |
"notes": f"http://{server_ip}/api/notes/", | |
"sleep": f"http://{server_ip}/api/sleep/", | |
"temperature": f"http://{server_ip}/api/temperature/", | |
"timers": f"http://{server_ip}/api/timers/", | |
"tummy-times": f"http://{server_ip}/api/tummy-times/", | |
"weight": f"http://{server_ip}/api/weight/" | |
} | |
token = '' # input babybuddy API key from admin-->settings page | |
authorization = { | |
"Authorization": f"Token {token}"} | |
def clean_keys(data: list) -> list: | |
""" | |
Convert ver 1.2.2 JSON format to match 1.4.0 format/keys | |
Parameters: | |
data (list): List of dicts | |
Returns: | |
data (list): List of dicts to match ver 1.4.0 schema | |
""" | |
print(data) | |
for _ in data: | |
_["child_id"] = _["child"] | |
del _["child"] | |
if "time" in _: | |
_["time"] = _["time"][:19].replace('T', ' ') | |
elif "start" in _ and "end" in _: | |
_["start"] = _["start"][:19].replace('T', ' ') | |
_["end"] = _["end"][:19].replace('T', ' ') | |
return data | |
def get_api_data(token: str, limit: str = 10_000, **endpoints: dict): | |
""" | |
Create JSON files with Baby Buddy API endpoint data | |
Parameters: | |
token (str): Authorization Token | |
limit (str): API get record limit | |
endpoints (dict): API endpoints | |
Returns: | |
file (JSON): End point JSON data | |
""" | |
for key, value in endpoints.items(): | |
url = f"{value}?limit={limit}" | |
r = session.get(url, headers=token) | |
data = r.json()["results"] | |
if key != "children" and key != "timers": # skip these files, missing "child" key | |
data = clean_keys(data) | |
file_name = f"{key}.json" | |
with open(file_name, 'w') as json_file: | |
json.dump(data, json_file) | |
get_api_data(authorization, **endpoints) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment