Consuming Reddit API

Consuming Reddit API

This is a simple way to consume the Reddit API, we are listing the most popular topics on Reddit from one specific subreddit

Below is the code to achieve this:

import requests
subreddit = 'python'
top_limit = 5
endpoint = f'https://www.reddit.com/r/{subreddit}/top.json?limit={top_limit}'

response = requests.get(endpoint, headers={'User-agent': 'Mozilla/5.0'})

if response.status_code == 200:
    data = response.json()
    for i, post in enumerate(data['data']['children']):
        print(f'{i+1}. Title: {post["data"]["title"]}\n    Score: {post["data"]["score"]}\n    URL: {post["data"]["url"]}\n')
else:
    print(f'Erro: {response.status_code}')

Output:

1. Title: I wrote a script to turn a satellite dish into a microwave camera
    Score: 179
    URL: https://www.reddit.com/r/Python/comments/1262jgy/i_wrote_a_script_to_turn_a_satellite_dish_into_a/

2. Title: Nanobind is a small binding library that exposes C++ types in Python and vice versa
    Score: 165
    URL: https://nanobind.readthedocs.io/en/latest/why.html

3. Title: I wrote a detailed guide of how Pandas' read_csv() function actually works and the different engine options available, including new features in v2.0. Figured it might be of interest here!
    Score: 72
    URL: https://medium.com/@finndersen/the-ultimate-guide-to-pandas-read-csv-function-5377874e27d5

4. Title: AITA? Unless building for a container (docker/k8s), always use a virtual environment for your projects.
    Score: 48
    URL: https://www.reddit.com/r/Python/comments/125xson/aita_unless_building_for_a_container_dockerk8s/

5. Title: Made a basic overhead game cam using a ray casting system I made
    Score: 23
    URL: https://www.reddit.com/r/Python/comments/126inuj/made_a_basic_overhead_game_cam_using_a_ray/

There are many possibilities for using the Reddit API, this is a very powerful resource for developers.