Stuck at API auth trying to use requests

I’m trying to build myself a little script to handle some DNS changes in bulk, but I’m stuck on the auth.

# setup structure so I can use mailinabox API to query DNS records
# starts with curl -X GET "https://{host}/admin/login" \
# -u "{username}:{password}"
# on success, it returns an API key "api_key"
# then I can use that key to query DNS records
# we will use requests library to do this
import requests as requests
import os
import base64

# credentials
host = "box.me.host"
username = os.environ["MAILINABOX_USERNAME"]
password = os.environ["MAILINABOX_PASSWORD"]

# Encode username and password as base64
credentials = f"{username}:{password}"
credentials_base64 = base64.b64encode(credentials.encode("utf-8"))

# Auth and get API key
login_url = f'https://{host}/admin/login'
headers = {
    "Authorization": f"Basic {credentials_base64}"
}
response = requests.get(login_url, headers=headers)

if response.status_code == 200:
    api_key = response.json().get('api_key')
    print(f'API key: {api_key}')
else:
    print(f'Error: Unable to get API key. Status code: {response.status_code}, Response: {response.text}')
    exit()

I might just be very tired and missing something extremely obvious, but any help will be greatly appreciated.

I think you need to do a

credentials_base64.decode("utf-8")

And put that in the headers.
Also, it’s requests.post not requests.get

And get some sleep :wink:

Thanks! That worked. I guess I misunderstand the API docs:

curl -X GET "https://{host}/admin/login" \
  -u "<email>:<password>"

Unless that has something to do with curl needing to be GET and requests via Python needing to be Post?

Might also be documentation error :innocent:

1 Like