Pocket API authorization from Python / Jupyter

419 views Asked by At

The following Python script should authorize me to use my Pocket app to retrieve documents. I'm running it from a Jupyter notebook.

import json
import pandas as pd
import requests
from urllib.parse import urlencode
from urllib.request import Request, urlopen

app_key = '<app key>'

request_token_url = 'https://getpocket.com/v3/oauth/request'

auth_params = {'consumer_key': app_key,
               'redirect_uri': redirect_url}

oauth = requests.post(request_token_url, data=auth_params)

token = oauth.text; print(token)

<........-....-....-....-......>

auth_url = 'https://getpocket.com/v3/oauth/authorize'
redirect_uri = '<jekyll-based static blog on github>'

usr_params = {'request_token': token, 'redirect_uri': redirect_uri}

usr = requests.post(auth_url, json = usr_params)

print(usr.text)

I consistently get a status code 400 back, but am unable to detect where the error is coming from. Thanks.

1

There are 1 answers

0
h1-the-swan On

First, add headers to your first POST request to get the response in JSON form:

headers={'X-Accept': 'application/json'}
oauth = requests.post(request_token_url, data=auth_params, headers=headers)
token = oauth.json()["code"]

Before your second POST request, you need to go to a web browser and manually authenticate your app. This is not something your script can handle automatically. To get the URL, you can do:

auth_url = 'https://getpocket.com/auth/authorize'
print(f"{auth_url}?request_token={token}&redirect_uri={redirect_uri}")

Go to this URL in your browser, authenticate your app. Then you can use the following to get an access token, which you can use in subsequent Pocket API calls:

access_token_url = 'https://getpocket.com/v3/oauth/authorize'
params = {
    'consumer_key': app_key,
    'code': token,
}
headers={'X-Accept': 'application/json'}
response = requests.post(access_token_url, params=params, headers=headers)
access_token = response.json()['access_token']

As a final note, you can use the Pocket API python wrapper (https://github.com/tapanpandita/pocket) to simplify this entire process a bit.