get reddit api credentials with praw
Share this post

This post is part of the Complete Guide on the Reddit API

In this post, we are going to generate the credentials necessary to run the Reddit API using Python and the PRAW wrapper.

Here is the file that we are going to create.

L’attribut alt de cette image est vide, son nom de fichier est image-48-1024x418.png.

That file, will be useful to post on Reddit using the API.

For this tutorial, you will need to have Python Installed first.

If you know nothing about Python, make sure that you start by reading the complete guide on Python for SEO.


Learn Python by subscribing to my Newsletter


1. Install PRAW

The first need that you will need to do is to install the praw package.

Open the Terminal and type in:

$ pip install praw

2. Create the client_secrets file

In a text editor, here I use VSCode, create a client_secrets.json file with that structure.

{
    "client_id":"",
    "client_secret":"",
    "user_agent":"script by u/yourusername",
    "redirect_uri":"http://localhost:8080",
    "refresh_token":""
}

Create the App

The first step is to create an application to query the API.

  1. Go to Reddit Apps
  2. Select “script” as the type of app.
  3. Name your app and give it a description.
  4. Set-up the redirect uri to be http://localhost:8080.

The redirect URI will be used to get your refresh token.

Create the app on Reddit

Once you click on “create app”, you will get a box showing you your client_id and client_secrets.

Imagine this as being your username and password to the API.

Copy those values in your client_secrets.json file.

3. Get the Refresh Token

Now that you have your client_id and client_secrets, it is time to generate a refresh token.

You Might Also Like  Recrawl URLs Extracted with Screaming Frog (using Python)

The refresh token will be useful to access the API without always re-approving the API.

To get the Refresh Token, PRAW made a Python script available to authorize the app.

Create a refreshtoken.py file in VSCode and add the following script.

#!/usr/bin/env python

"""This example demonstrates the flow for retrieving a refresh token.

In order for this example to work your application's redirect URI must be set to
http://localhost:8080.

This tool can be used to conveniently create refresh tokens for later use with your web
application OAuth2 credentials.

"""
import random
import socket
import sys

import praw


def receive_connection():
    """Wait for and then return a connected socket..

    Opens a TCP connection on port 8080, and waits for a single client.

    """
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server.bind(("localhost", 8080))
    server.listen(1)
    client = server.accept()[0]
    server.close()
    return client


def send_message(client, message):
    """Send message to client and close the connection."""
    print(message)
    client.send(f"HTTP/1.1 200 OK\r\n\r\n{message}".encode("utf-8"))
    client.close()


def main():
    """Provide the program's entry point when directly executed."""
    print(
        "Go here while logged into the account you want to create a token for: "
        "https://www.reddit.com/prefs/apps/"
    )
    print(
        "Click the create an app button. Put something in the name field and select the"
        " script radio button."
    )
    print("Put http://localhost:8080 in the redirect uri field and click create app")
    client_id = input(
        "Enter the client ID, it's the line just under Personal use script at the top: "
    )
    client_secret = input("Enter the client secret, it's the line next to secret: ")
    commaScopes = input(
        "Now enter a comma separated list of scopes, or all for all tokens: "
    )

    if commaScopes.lower() == "all":
        scopes = ["*"]
    else:
        scopes = commaScopes.strip().split(",")

    reddit = praw.Reddit(
        client_id=client_id.strip(),
        client_secret=client_secret.strip(),
        redirect_uri="http://localhost:8080",
        user_agent="praw_refresh_token_example",
    )
    state = str(random.randint(0, 65000))
    url = reddit.auth.url(scopes, state, "permanent")
    print(f"Now open this url in your browser: {url}")
    sys.stdout.flush()

    client = receive_connection()
    data = client.recv(1024).decode("utf-8")
    param_tokens = data.split(" ", 2)[1].split("?", 1)[1].split("&")
    params = {
        key: value for (key, value) in [token.split("=") for token in param_tokens]
    }

    if state != params["state"]:
        send_message(
            client,
            f"State mismatch. Expected: {state} Received: {params['state']}",
        )
        return 1
    elif "error" in params:
        send_message(client, params["error"])
        return 1

    refresh_token = reddit.auth.authorize(params["code"])
    send_message(client, f"Refresh token: {refresh_token}")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Run it in your Terminal using:

$ python refreshtoken.py

A series of prompts will ask you to add your client_id and client_secrets.

Then, one last prompt will ask you to add scopes to the API (what are you allowed to do with the credentials).

You Might Also Like  Why Learn Python for SEO (By Elias Dabbas)

You can find a list of scopes in Reddit official documentation.

For simplicity, I will use “all”, for “all scopes”.

Now, copy the url in your browser and authorize the app.

You will be redirected to a page where you access token is printed.

Copy the refresh token into your client_secrets.json file.

L’attribut alt de cette image est vide, son nom de fichier est image-48-1024x418.png.

What’s Next?

Get Top Posts From Subreddit With Reddit API and Python

Reddit API JSON’s Documentation

How to use Reddit API With Python (Pushshift)

Get Reddit API Credentials with PRAW (Authentication)

Post on Reddit API With Python (PRAW)

Show Random Reddit Post in Terminal With Python

Conclusion

That’s it! You now have everything that you need to use the Reddit API with the PRAW Wrapper.

The next step is to make a post into a subreddit!.