Shatnerz
Shatnerz

Reputation: 2543

Python requests and instagram

I am playing around with the instagram api and requests, trying to get past the OAuth. I use r = requests.get(...) and follow the instagram doc. However, the output from requests is never what I expect. I am having 2 issues that are somewhat similar.

1) If I send the wrong parameters I expect to get back JSON looking like

{"code": 400, "error_type": "OAuthException", "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}

Which is what I see if I paste the string from r.url into the browser. However r.json() simply fails and gives me

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

2) A correct response should redirect me to my redirect url, which will also include a code. Again, this works correctly when pasting r.url into a browser. I am successfully redirected as expected. Requests does not appear to redirect me, even with explicitly set allow_redirects=False. I only need to read the code from the url. How can I get requests to give me the final url for me to extract the code?

Edit: Might as well include some code.

def get_code(client_id, redirect_uri, scope="basic"):
    params = {"client_id": client_id,
              "redirect_uri": redirect_uri,
              "response_type": "code",
              "scope": scope}
    r = requests.get('https://api.instagram.com/oauth/authorize/',
                     params=params)
    # print r.url
    # print r.json()
    return r

Upvotes: 0

Views: 3163

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

It tells you in the documentation exactly what happen, At this point, we present the user with a login screen and then a confirmation screen where to grant your app access to her Instagram data, if you run the snippet below you will see a login box in your browser:

import requests
import  webbrowser
from tempfile import NamedTemporaryFile
params = {"client_id": client_id,
          "redirect_uri": redirect_uri,
          "response_type": "code",
          "scope": scope}
with NamedTemporaryFile(dir=".", delete=0) as f:
    r = requests.get('https://api.instagram.com/oauth/authorize/',
                     params=params)
    f.write(r.content)
    webbrowser.open(f.name)

Upvotes: 1

Related Questions