For future reference, this codes works for me:
import requests # pip install requests
import jwt # pip install pyjwt
from datetime import datetime as date
# Admin API key goes here
key = ''
# Split the key into ID and SECRET
id, secret = key.split(':')
# Prepare header and payload
iat = int(date.now().timestamp())
header = {'alg': 'HS256', 'typ': 'JWT', 'kid': id}
payload = {
'iat': iat,
'exp': iat + 5 * 60,
'aud': '/admin/'
}
# Create the token (including decoding secret)
token = jwt.encode(payload, bytes.fromhex(secret), algorithm='HS256', headers=header)
# Make an authenticated request to create a post
url = 'https://ghost.test.com/ghost/api/admin/images/upload/'
headers = {'Authorization': 'Ghost {}'.format(token)}
with open("test.jpg", "rb") as file:
files = {'file': ('test.jpg', file, 'image/jpeg')}
r = requests.post(url, files=files, headers=headers)
print(r.json())
It seems to be important to explicitely set the MIME type, as to image/jpeg
in this example. I still had to install the sharp image processing library to make upload with python work.