I’ve made this site where you search for a keyword and tell games from different platforms using APIs (so far, Steam and Epic Games) but I get this error, here’s my code:
from flask import Flask, request, render_template
from steam_web_api import Steam
from dotenv import load_dotenv
import json
from typing import NamedTuple
import os
import requests
# Loads package from Epic Games Store API
from epicstore_api.exc import EGSException, EGSNotFound
from epicstore_api.models import EGSCategory, EGSCollectionType, EGSProductType
from epicstore_api.queries import STORE_QUERY
class OfferData(NamedTuple):
namespace: str
offer_id: str
__all__ = ['EpicGamesStoreAPI', 'OfferData']
class EpicGamesStoreAPI:
"""Class for interacting with EGS web API without user credentials."""
def __init__(self, locale="en-US", country="US", session=None) -> None:
self._session = requests.Session() or session
self.locale = locale
self.country = country
def _clean_1004_errors(self, raw):
if 'errors' in raw:
for error in raw['errors'].copy():
service_response = json.loads(error.get('serviceResponse', {}))
if service_response and service_response.get('numericErrorCode') == 1004:
raw['errors'].remove(error)
if not raw['errors']:
raw.pop('errors')
return raw
def _make_graphql_query(self, query, headers, **variables):
url = 'https://graphql.epicgames.com/graphql'
payload = {'query': query, 'variables': variables}
print(f"Payload: {json.dumps(payload, indent=2)}") # Print the payload for debugging
response = self._session.post(url, json=payload, headers=headers)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(f"HTTPError: {e.response.text}") # Print the response content for debugging
raise
return self._clean_1004_errors(response.json())
def fetch_store_games(
self,
count: int = 30,
product_type: str = 'ALL_PRODUCTS',
allow_countries: str = 'US',
namespace: str = '',
sort_by: str = 'title',
sort_dir: str = 'ASC',
release_date: str | None = None,
start: int = 0,
keywords: str = '',
categories: list[EGSCategory] | str | None = None,
*,
with_price: bool = True,
) -> dict:
sort_dir = sort_dir.upper()
if sort_dir not in ('ASC', 'DESC'):
raise ValueError(f'Parameter ``sort_dir`` have to be equals to ASC or DESC, not to {sort_dir}')
if categories is None:
categories = ''
return self._make_graphql_query(
STORE_QUERY,
headers={'content-type': 'application/json;charset=UTF-8'},
count=count,
category=product_type,
allowCountries=allow_countries,
namespace=namespace,
sortBy=sort_by,
sortDir=sort_dir,
releaseDate=release_date,
start=start,
keywords=keywords,
tag=categories,
withPrice=with_price
)
# Define the GraphQL query
STORE_QUERY = """
query searchStoreQuery(
$allowCountries: String
$category: String
$namespace: String
$sortBy: String
$sortDir: String
$start: Int
$tag: String
$releaseDate: String
$withPrice: Boolean = true
$keywords: String
$count: Int
) {
Catalog {
searchStore(
allowCountries: $allowCountries
category: $category
count: $count
country: "US"
keywords: $keywords
namespace: $namespace
sortBy: $sortBy
sortDir: $sortDir
releaseDate: $releaseDate
start: $start
tag: $tag
) {
elements {
title
description
keyImages {
type
url
}
seller {
name
}
categories {
path
}
price(country: "US") @include(if: $withPrice) {
totalPrice {
fmtPrice(locale: "en-US") {
discountPrice
}
}
}
productSlug
}
}
}
}
"""
# Load environment variables from .env
load_dotenv()
app = Flask(__name__)
steam_api_key = os.environ.get("STEAM_API_KEY")
if not steam_api_key:
raise ValueError("STEAM_API_KEY environment variable not set.")
steam = Steam(steam_api_key)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search', methods=['POST'])
def search():
search_query = request.form.get('search_query')
try:
# Fetch Steam games
steam_games = steam.apps.search_games(search_query)
for game in steam_games['apps']:
game['name'] = game['name'].encode('utf-8').decode('unicode_escape')
# Fetch all Epic Games Store games
epic_api = EpicGamesStoreAPI()
epic_games_response = epic_api.fetch_store_games(
product_type='games/edition/base|bundles/games|editors',
count=30,
sort_by='releaseDate',
sort_dir='DESC',
keywords=search_query,
with_price=True,
)
# Extract the relevant part of the response
epic_games = epic_games_response.get('Catalog', {}).get('searchStore', {}).get('elements', [])
# Print the Epic Games Store response for debugging
print(f"Epic Games Store Response: {json.dumps(epic_games, indent=2)}")
return render_template('results.html', steam_games=steam_games, epic_games=epic_games)
except Exception as e:
print(f"An error occurred: {e}")
return str(e), 500
if __name__ == '__main__':
app.run(debug=True)
and this is the error:
An error occurred: ‘list object’ has no attribute ‘data’
pls help
At first the site wouldnt load, then i got help and made the search site load but then the error would pop up.
New contributor
Scorpio is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.