"Upload: Create" API key insufficient?

I’m using the following code to upload through the API:

# And ask Discourse where to send it.
r = requests.post(
    f"https://{DISCOURSE}/uploads/generate-presigned-put", json=file_info, headers=HEADERS)
if r.status_code != 200:
    print(
        f"Error asking where to upload the image: got {r.status_code}", file=sys.stderr)
    sys.exit(1)

upload_url = r.json()['url']
upload_uid = r.json()['unique_identifier']

# Now put it where we were told to.
r = requests.put(upload_url, data=image_data)
if r.status_code != 200:
    print(
        f"Error uploading image to external storage: got {r.status_code}", file=sys.stderr)
    sys.exit(1)

# And tell Discourse that it worked, and get back an id we can reference later.
r = requests.post(f"https://{DISCOURSE}/uploads/complete-external-upload",
                  data=f'unique_identifier={upload_uid}', headers=HEADERS)
if r.status_code != 200:
    print(f"Error completing upload: got {r.status_code}", file=sys.stderr)
    sys.exit(1)
image_id = r.json()['id']

This works with an “all access” API key, but when I try to use a granular one with the “uploads: create” scope, I get a 403 error on post to /uploads/generate-presigned-put.

2 Likes

Nice catch, we will get this sorted, keep in mind the protocol is somewhat more complex now that we upload directly to s3.

2 Likes

I have only started using thr API for this after you switched, so as far as I know this is the normal level of complication. :slight_smile:

Are there situations where the following isn’t sufficient?

  1. POST file info to /uploads/generate-presigned-put
    • result includes a remote URL to upload to (which includes authentication parameters) and a unique upload ID
  2. PUT image data to the URL from above
    • handle error if this fails
  3. POST upload ID from above to /uploads/complete-external-upload
    • result is an image ID one can use other places in the API (like badge creation)

Hi @mattdm I’ve updated the API key scope to cover these new actions for our direct upload flow, and I’ve deployed your site too, please let me know if you still have further issues.

Confirmed! Works now. Thanks!

3 Likes

This topic was automatically closed after 20 hours. New replies are no longer allowed.