Laying the Groundwork for Your App
00:00 In this lesson, you’ll be building a command line app to read comments on GitHub issues from the GitHub web API. The API’s responses are large nested JSON objects containing info about a given GitHub repository.
00:12 Since you’ll want to extract and print specific elements of these JSON objects, structural pattern matching is the perfect tool. First, you can take a peek at the JSON by running the following line in the terminal.
00:25
curl
makes a request to the URL. jq
parses and purifies the JSON. And in this case, head
shows the first 24 lines of the result.
00:34
You don’t have to use head
, but I’ll warn you, this is a pretty huge JSON. You can read from the URL that we’re getting event data from the CPython repository in the Python organization on GitHub.
00:45 This is the main development branch of CPython. Feel free to pause and examine this JSON before moving on. Remember, ultimately you want to extract issue comments from these JSON objects and you can think of the structure returned here as a list of dictionaries, each dictionary describing one event.
01:03
Now moving to the IDE, get started by writing a function to extract events from a repo on GitHub by providing the organization and repository names. Import the json
library, import urllib.
request
. def fetch_github_events(
taking in the arguments org
and repo
, create a variable called url
that holds the f-string of the GitHub URL we just used using string interpolation to supply the organization and repository elements of that string.
01:38
Now using urllib.request.urlopen(
01:44 you make a GET request to the URL
01:48 and the next line, load the JSON as a Python object, in this case a list of dictionaries, and return it. Next, create the template for displaying each comment.
01:59
You’ll define a few replacement fields with named arguments and later call the .format()
method on this string to populate them. It’s going to be a constant, so it should come before the functions. COMMENT_TEMPLATE
equals the multi-line string: first line Issue Title:
followed by the replacement argument {issue_title}
an empty line, a line with three dashes, a line with the replacement argument {body}
.
02:25
Another empty line, another set of three dashes. Comment by:
replacement argument {user}
- {user_url}
02:37
another empty line, and then the replacement argument {when}
followed by the replacement argument {url}
.
Become a Member to join the conversation.