curl request with environment variable works but fails on python3 requests

Viewed 258

I am trying to convert this working curl command:

curl ipinfo.io/8.8.8.8/json?token=$TOKEN

to python3 requests. This is my current script:

#!/usr/bin/env python3
import requests

def getIPInfo ():
    params = (
    ('token', '$TOKEN'),
    )

    response = requests.get('http://ipinfo.io/8.8.8.8/json', params=params)
    
    print(response)

getIPInfo()

However, when I run it, I get back "Error 403"?

<Response [403]>
2 Answers

The $TOKEN part of your cURL command actually pulls a value from the environment. You need to use os.environ to accomplish the same thing in Python.

Also, I would use a dict for the params as it's a bit more clear than the tuple of tuples.

#!/usr/bin/env python3
import requests
import os

def getIPInfo ():
    params = {
        'token': os.environ.get('TOKEN'),
    }

    response = requests.get('http://ipinfo.io/8.8.8.8/json', params=params)
    
    print(response)

getIPInfo()

Why do I get back "Error 403"?

Because you are passing literally "$TOKEN" as the token. Instead, you need to pass in a valid auth token.

Related