Hi all!
One quick questions about a thing I’m trying to do in Django Python: I’m setting up a signal that creates/updates the user data to Klaviyo when the user is created/updated.
I tried to do the same via http requests in the same environment (same key, same objects) and it all works.
When trying with the Python API, it returns an unathorized error (401). I troubleshooted the issue checking:
- that the key has both the string and the key, it has
- that the key has the correct permissions, it has
At this point I’m out of all ideas. I’m afraid something is missing from my code, but as far as I saw on the guides on GitHub I cannot find the missing element.
My code is this:
from django.conf import settings
from klaviyo_api import KlaviyoAPI
import pprint
import traceback
private_key = settings.KLAVIYO_PRIVATE_KEY
klaviyo = KlaviyoAPI(api_key=private_key, max_delay=5, max_retries=3)
def create_update_profile(user):
payload = {
"data": {
"type": "profile",
"attributes": {
"email": user.email,
"phone_number": user.prefix + user.phone,
"external_id": str(user.id),
"first_name": user.first_name,
"last_name": user.last_name,
"location": {
"address1": user.address,
"city": user.city,
"country": "Italy",
"region": user.province,
"zip": user.zipCode,
"timezone": "Europe/Rome"
},
"properties": {
"Gender": user.gender,
"Birthday": user.birthday.strftime('%Y-%m-%d')
}
}
}
}
try:
k_profile = klaviyo.Profiles.create_or_update_profile(payload)
pprint(f'Job done: {k_profile}')
return k_profile
except Exception as e:
pprint.pprint(e)
traceback.print_exc()
return None
And this is the error:
openapi_client.exceptions.UnauthorizedException: (401)
Reason: Unauthorized
HTTP response headers: HTTPHeaderDict({'Date': 'Mon, 30 Sep 2024 09:07:41 GMT', 'Content-Type': 'application/vnd.api+json', 'Content-Length': '264', 'Connection': 'keep-alive', 'CF-Ray': '8cb31067ca4dbabe-MXP', 'CF-Cache-Status': 'DYNAMIC', 'Allow': 'POST, OPTIONS', 'Content-Language': 'en-us', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload', 'Vary': 'Accept-Language, Cookie, Accept-Encoding', 'WWW-Authenticate': 'Bearer, Klaviyo-API-Key', 'Content-Security-Policy': "script-src 'report-sample' 'strict-dynamic' 'unsafe-eval'; object-src 'none'; base-uri 'none'; frame-ancestors 'self' login.bigcommerce.com *.mybigcommerce.com admin.shopify.com klaviyo.file.force.com klaviyo.lightning.force.com klaviyo.my.salesforce.com; report-uri /csp/", 'X-Content-Type-Options': 'nosniff', 'X-Robots-Tag': 'noindex, nofollow', 'Server': 'cloudflare'})
HTTP response body: errors=[GetAccounts4XXResponseErrorsInner(id='e8249737-283b-4db2-b1b1-fa324fe71f02', code='not_authenticated', title='Authentication credentials were not provided.', detail='Missing or invalid authorization scheme. Please use Klaviyo-API-Key.', source=GetAccounts4XXResponseErrorsInnerSource(pointer='/data/', parameter=None))]
Can any of you help me out on this?
Thank you in advance!
Federico