Я отправляю запросы на API-интерфейс ticketmaster discovery v2. Я отправил запросы и получил желаемый ответ, используя метод, где мой ключ API встроен в URL. Однако, когда я изменяю свой код, чтобы использовать заголовок авторизации вместо встраивания в URL, код перестает работать вообще и возвращает ошибку.
Я новичок в API, и документация API Ticketmaster относительно редка в отношении синтаксиса для заголовков аутентификации, поэтому второй (более опытный) взгляд на мой код может помочь раскрыть мою ошибку.
Мне любопытно, если я допустил синтаксическую ошибку в своем коде, что привело к отсутствию желаемого ответа.
Если мой синтаксис не является проблемой, мне было бы интересно услышать другие идеи или способы устранения неполадок, которые могут раскрыть проблему.
Я пытался изменить как можно меньше между первым и вторым фрагментом кода. Оба они генерируют одну и ту же строку URL, за исключением встроенного ключа API. Таким образом, я считаю, что мой синтаксис заголовка может быть виновником, но мне не хватает опыта REST API, чтобы знать наверняка.
import requests
import json
import sqlite3
from datetime import datetime
import keys
def date(datestr, format = "%Y-%m-%d %H:%M:%S"): # a function to print out the date/time
# of the event in a nice way
d = datetime.strptime(datestr, format)
pretty = d.strftime("%a, %b %d, %Y at %H:%M")
return pretty
ticketmaster_key = keys.ticketmaster_key #assign ticketmaster key from keys file
CACHE_FNAME = "ticketmaster_cache.json" #create a cache for ticketmaster events
try:
cache_file = open(CACHE_FNAME, "r") #try to read file
cache_contents = cache_file.read() #if it's there, read it as a string
CACHE_DICTION = json.loads(cache_contents) #load it as a dictionary
cache_file.close() #close file
except:
CACHE_DICTION = {} #Creates empty dictionary object called CACHE_DICTION
def get_event_info(search, ticketmaster_key = ticketmaster_key): #function to get event info from ticketmaster
#it either gets from the cache if it's there or
if search in CACHE_DICTION: #requests from the API
d = CACHE_DICTION[search]
else: #the params for the URL include the search, key,
data = requests.get("https://app.ticketmaster.com/discovery/v2/events", #format, dmaId which is the New York code, size of response
params = {"keyword": search, "apikey": ticketmaster_key, #sends GET request to ticketmaster.com website
"format":"json", "dmaId": "366", "size": 200, "radius": "2"})
print(data.url)
d = json.loads(data.text) #takes text from "data" variable and saves as a json object named d
CACHE_DICTION[search] = d #saves json object "d" into cache dictionary
f = open(CACHE_FNAME, 'w') #Opens cache with filename CACHE_FNAME for writing.
f.write(json.dumps(CACHE_DICTION)) #Writes json object called CACHE_DICTION to CACHE_FNAME
f.close() #Closes cache file called CACHE_FNAME
return d
ticket_search = get_event_info("") #search Ticketmaster for keyword contained in quotes
print(ticket_search)
----------------------------------------------- ----------------------------
import requests
import json
import sqlite3
from datetime import datetime
# Variable to store API token for ticketmaster API
api_token = "g4uj38J6W2KKNGizVchZ3mgdwkOgIXJr"
# Variable to store base url for API string
api_url_base = "https://app.ticketmaster.com/discovery/v2/"
# HTTP header
headers = {'Content-Type':'application/json','Authorization':'Bearer {0}'.format(api_token)}
# a function to print out the date/time in a pretty way
def date(datestr, format="%Y-%m-%d %H:%M:%S"):
d = datetime.strptime(datestr, format)
pretty = d.strftime("%a, %b %d, %Y at %H:%M")
return pretty
# Create json file for caching and store in local variable
CACHE_FNAME = "ticketmaster_cache.json"
try:
# Open cache file for reading and assign file pointer
cache_file = open(CACHE_FNAME, "r")
# Read contents of cache file and store in local variable
cache_contents = cache_file.read()
# Load contents to dictionary object
CACHE_DICTION = json.loads(cache_contents)
# Close file pointed to by file pointer
cache_file.close()
# Create new empty dictionary if none existed previously
except:
CACHE_DICTION = {}
def get_event_info(search):
if search in CACHE_DICTION:
d = CACHE_DICTION[search]
else:
api_url = '{0}events'.format(api_url_base)
payload = {"keyword": search, "dmaId": "366", "size": 200, "radius": "2"}
data = requests.get(api_url, headers=headers, params=payload)
print(data.url)
d = json.loads(data.text)
CACHE_DICTION[search] = d
f = open(CACHE_FNAME, 'w')
f.write(json.dumps(CACHE_DICTION))
f.close()
return d
ticket_search = get_event_info("music")
print(ticket_search)
Когда я запускаю фрагмент кода, который использует аутентификацию на основе заголовка, сгенерированная строка URL выглядит следующим образом:
https://app.ticketmaster.com/discovery/v2/events?keyword=music&dmaId=366&size=200&radius=2
И возвращается ошибка:
{'fault': {'faultstring': 'Не удалось разрешить переменную API Key request.queryparam.apikey', 'detail': {'errorcode': 'steps.oauth.v2.FailedToResolveAPIKey'}}}