Search code examples
pythonreddit

How to exchange code for access token with Reddit API


I'm sure this is a broader question that applies to more than just Reddit, but currently I am attempting to exchange a code for a user access token however I am not understanding how to implement the following steps:

https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token

If you didn't get an error and the state value checks out, you may then make a POST request with code to the following URL to retrieve your access token:

https://www.reddit.com/api/v1/access_token

Include the following information in your POST data (NOT as part of the URL)

grant_type=authorization_code&code=CODE&redirect_uri=URI

Okay, so what I did was this:

headers = {
     CLIENT_ID: CLIENT_SECRET,
    }
r = requests.post(
    url="https://www.reddit.com/api/v1/access_token",
    data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": "http://127.0.0.1:5000/callback"
      },
    headers=headers
  )

I think I am failing with the headers, I receive a 429 error, and I don't think I've understood how to arrange the headers correctly as it doesn't clearly explain in the above link.

The "user" is the client_id. The "password" for confidential clients is the client_secret. The "password" for non-confidential clients (installed apps) is an empty string.

CLIENT_ID and CLIENT_SECRET are obviously variables, and they are my Reddit App dev credentials.

EDIT:

I came up with this, it's gross but it seems to work

headers = {
        "User-Agent": "MyApp v1.0",
        "Authorization": "Basic " + str(base64.b64encode(str.encode(f"{CLIENT_ID}:{CLIENT_SECRET}")))[2:-1],
    }

Is there a cleaner way to write that?


Solution

  • Final answer, using an inbuilt method in Python's request:

    client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
    
    r = requests.post(
        url="https://www.example.com/api/v1/access_token",
        auth=client_auth,
        data={
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": "http://127.0.0.1:5000/callback"
        },
        headers={
            "User-Agent": "MyApp v1.0",
        }
    )