Thanks for being a part of WWDC25!

How did we do? We’d love to know your thoughts on this year’s conference. Take the survey here

Apple Search Ads API – 401 Unauthorized (Invalid Token) Issue

import requests import time import json import gspread import base64 import hashlib from oauth2client.service_account import ServiceAccountCredentials from datetime import datetime, timedelta, timezone from cryptography.hazmat.primitives import serialization, hashes from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.backends import default_backend import jwt

def base64url_encode(data): return base64.urlsafe_b64encode(data).rstrip(b'=')

def generate_apple_jwt(): with open(PRIVATE_KEY_PATH, "rb") as key_file: private_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend() )

headers = {
    "alg": "ES256",
    "kid": KEY_ID,
    "typ": "JWT"
}

payload = {
    "iss": TEAM_ID,
    "sub": CLIENT_ID,
    "aud": "https://api.searchads.apple.com",
    "iat": int(time.time()),
    "exp": int(time.time()) + 3600,
}

header_bytes = base64url_encode(json.dumps(headers, separators=(',', ':')).encode('utf-8'))
payload_bytes = base64url_encode(json.dumps(payload, separators=(',', ':')).encode('utf-8'))
signing_input = header_bytes + b'.' + payload_bytes

signature = private_key.sign(
    signing_input,
    ec.ECDSA(hashes.SHA256())
)

jwt_token = signing_input + b'.' + base64url_encode(signature)

return jwt_token.decode('utf-8')

what is wrong??

this code occurs this error... It's frustrating not being able to figure out what's wrong.

{"data":null,"pagination":null,"error":{"errors":[{"messageCode":"UNAUTHORIZED","message":"Invalid token: 2bea5cf6-94e0-4c1f-b144-e5799172968d","field":""}]}}

same error, have you resolved it ?

Apple Search Ads API – 401 Unauthorized (Invalid Token) Issue
 
 
Q