Anatomy of a Python Program

Let’s take a very quick look at a Python program that uses the GitHub Search API to display a list of popular repositories in three different programming languages, sorted by the amount of stars that they have. It may be hard to believe, but by the end of the day, you’ll be able to write a program just like this.

A Python program for using the GitHub search API

"""
A small Python program that uses the GitHub search API to list
the top projects by language, based on stars.
"""

import requests

GITHUB_API_URL = "https://api.github.com/search/repositories"


def create_query(languages, min_stars=50000):
    query = f"stars:>{min_stars} "

    for language in languages:
        query += f"language:{language} "

    # a sample query looks like: "stars:>50 language:python language:javascript"
    return query


def repos_with_most_stars(languages, sort="stars", order="desc"):
    query = create_query(languages)
    params = {"q": query, "sort": sort, "order": order}

    response = requests.get(GITHUB_API_URL, params=params)
    status_code = response.status_code

    if status_code != 200:
        raise RuntimeError(f"An error occurred. HTTP Code: {status_code}.")
    else:
        response_json = response.json()
        return response_json["items"]


if __name__ == "__main__":
    languages = ["python", "javascript", "ruby"]
    results = repos_with_most_stars(languages)

    for result in results:
        language = result["language"]
        stars = result["stargazers_count"]
        name = result["name"]

        print(f"-> {name} is a {language} repo with {stars} stars.")

Step by step

Expand this section to walk through the program step-by-step.

End Result

The end result looks something like this:

(env) $ python dayone.py

-> freeCodeCamp is a JavaScript repo with 298046 stars.
-> bootstrap is a JavaScript repo with 131403 stars.
-> vue is a JavaScript repo with 130099 stars.
-> react is a JavaScript repo with 123969 stars.
-> d3 is a JavaScript repo with 82932 stars.
-> javascript is a JavaScript repo with 82514 stars.
-> react-native is a JavaScript repo with 74810 stars.
-> create-react-app is a JavaScript repo with 64725 stars.
-> awesome-python is a Python repo with 63693 stars.
... and more results

Don’t worry if you didn’t understand this code, we’ll be building this program in the workshop today.