Repository navigation
Expand file tree
/
Copy pathrequests_example.py
More file actions
102 lines (90 loc) · 3.67 KB
/
Copy pathrequests_example.py
File metadata and controls
102 lines (90 loc) · 3.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
"""GitHub scraper API: requests example.
Runs DataGuru's GitHub APIs and prints the JSON they return:
- GitHub AI Dataset & Documentation Collection: $0.0022 per successful request ($2.20 per 1,000)
- GitHub Repository Details & Metrics: $0.0022 per successful request ($2.20 per 1,000)
- GitHub Developer Talent Sourcing & Profiles: $0.0022 per successful request ($2.20 per 1,000)
Setup:
pip install -r requirements.txt
export DATAGURU_API_KEY="your key" # free credit at https://dashboard.dataguru.cc
Run:
python examples/requests_example.py
python examples/requests_example.py github-dataset-collection
"""
import json
import os
import re
import sys
import requests
API_KEY = os.environ.get("DATAGURU_API_KEY") or sys.exit("Set DATAGURU_API_KEY (https://dashboard.dataguru.cc)")
# Every GitHub API: endpoint, method and example input. Parameters go in the query string or the
# JSON body as each endpoint expects. "from" means the input URL is taken from another API's results.
# Entries marked needs_input hold a placeholder value: replace it, then run that API by name.
CALLS = {
"github-dataset-collection": {
"name": "GitHub AI Dataset & Documentation Collection",
"method": "POST",
"url": "https://api.dataguru.cc/api/v1/github/dataset-collection",
"query": {},
"body": {
"target": "psf/requests"
}
},
"github-repo-details": {
"name": "GitHub Repository Details & Metrics",
"method": "POST",
"url": "https://api.dataguru.cc/api/v1/github/repo-details",
"query": {},
"body": {
"target": "tiangolo/fastapi"
}
},
"github-talent-sourcing": {
"name": "GitHub Developer Talent Sourcing & Profiles",
"method": "POST",
"url": "https://api.dataguru.cc/api/v1/github/talent-sourcing",
"query": {},
"body": {
"target": "<github-username>"
},
"needs_input": True
}
}
def run(session, name, results):
"""Calls one API (and the search it depends on, if any) and returns its JSON."""
if name in results:
return results[name]
call = CALLS[name]
query, body = dict(call["query"]), dict(call["body"])
if "from" in call:
src = call["from"]
match = re.search(src["match"], json.dumps(run(session, src["api"], results)))
if not match:
raise RuntimeError(f"No URL found in the {src['api']} results")
(query if src["param"] in query else body)[src["param"]] = match.group(0)
response = session.request(
call["method"], call["url"], params=query or None,
json=body if call["method"] != "GET" else None, timeout=300,
)
data = response.json()
if response.status_code >= 400 or data.get("success") is False:
error = data.get("error") or {}
raise RuntimeError(f"{name}: HTTP {response.status_code} {error.get('code')}: {error.get('message')}")
results[name] = data
return data
def main(names):
with requests.Session() as session:
session.headers["Authorization"] = f"Api-Key {API_KEY}"
results = {}
for name in names:
data = run(session, name, results)
print(f"== {CALLS[name]['name']} ({name})")
print(json.dumps(data, indent=2, ensure_ascii=False)[:1500])
if __name__ == "__main__":
names = sys.argv[1:] or [n for n, c in CALLS.items() if not c.get("needs_input")]
unknown = [n for n in names if n not in CALLS]
if unknown:
sys.exit(f"Unknown API {unknown}. Choose from: {', '.join(CALLS)}")
try:
main(names)
except (requests.RequestException, RuntimeError) as error:
sys.exit(str(error))