This is a sample code to get a list of articles posted by users with Python 3 and Qiita API v2.
In this post, I call the API every time to download JSON, but in reality it is better to save it locally and refer to it because of its kindness to the server (and the number of times limit).
import json
import urllib.request
from pprint import pp
def get_qiita_user_url(username):
if not isinstance(username, str):
raise TypeError()
return f"https://qiita.com/api/v2/users/{username}"
def fetch_qiita_user(username):
url = get_qiita_user_url(username)
with urllib.request.urlopen(url) as f:
return json.load(f)
def get_qiita_useritems_url(username, page, per_page):
if not isinstance(username, str):
raise TypeError()
if not isinstance(page, int) or not isinstance(per_page, int):
raise TypeError()
if not (1 <= page <= 100) or not (1 <= per_page <= 100):
raise ValueError()
return f"https://qiita.com/api/v2/users/{username}/items?page={page}&per_page={per_page}"
def fetch_qiita_useritems(username, page, per_page):
url = get_qiita_useritems_url(username, page, per_page)
with urllib.request.urlopen(url) as f:
return json.load(f)
def fetch_qiita_userallitems(username):
userinfo = fetch_qiita_user(username)
itemcount = userinfo["items_count"]
useritems = []
for page in range(1, 100):
fetched = (page - 1) * 100
if fetched > itemcount:
break
useritems.extend(fetch_qiita_useritems(username, page, 100))
page += 1
return useritems
#Specify your user name for the time being
username = "katabamisan"
useritems = fetch_qiita_userallitems(username)
titles = [entry["title"] for entry in useritems]
pp(titles)
According to the Qiita API v2 documentation, the API returns a response containing an object that represents an error on failure. On the other hand, Python 3's ʻurllib.request` raises an exception because the status code at this time is an error. This post doesn't specifically handle the error object, assuming that the caller of the function handles the exception.
Recommended Posts