Search code examples
pythonbit.ly

403 error when accessing bit.ly API to shorten URL with Python


Here's the code I'm using:

import re
import sys
import glob
import json
import requests
import os
from pprint import pprint

if len(sys.argv) > 1:
    urls_json = sys.argv[1]
else:
    urls_json = "enlaces.json"

with open( urls_json ) as data_file:
    urls = json.load(data_file)

api_key = os.environ["BITLY_TOKEN"]
group_guid = os.environ["BITLY_USER"]

shortened_links = []
for u in urls:
    payload = json.dumps({'long_url': u[1], "domain": "bit.ly", "group_guid": group_guid })
    print(payload)
    response = requests.post( "https://api-ssl.bitly.com/v4/shorten",
                              data=payload,
                              headers={'Authorization': f"Bearer {api_key}" } )
    pprint(vars(response.raw))
    pprint(vars(response.request))

This consistently returns a 403 forbidden. The header is correct but I'm not so sure about the group_guid; I'm using my username for that. I obtained the token by issuing a curl request to the API. Any idea? Is this correct?


Solution

  • Just eliminate the group_guid:

        payload = json.dumps({'long_url': u[1], "domain": "bit.ly" })
    

    Despite being clearly indicated in the API documentation as one of the parameters. That returns a 201 for "Created"