Search code examples
pythonapireddit

How to read top 10 headlines from the front page of Reddit using it's API?


I am new to Python and I want to use Reddit API to retrieve top 10 headline on the front page of Reddit using Python. I tried to read the API documentation but I am not able to understand how to proceed.

It would be great if someone can give me an example.

Thanks


Solution

  • Here's a quick example on how to download the json data you want. Basically, open the URL, download the data in JSON format, and use json.loads() to load it into a dictionary.

    try:
        from urllib.request import urlopen
    except ImportError:  # Python 2
        from urllib2 import urlopen
    
    import json
    
    url = 'http://www.reddit.com/r/python/.json?limit=10'
    jsonDownload = urlopen(url)
    jsonData = json.loads(jsonDownload.read())
    

    From there, you can print out 'jsonData', write it to a file, parse it, whatever.