NOTE: Get an APIKey.
This code will allow you to get a session, fetch account info, upload a file, and search games. From it you should be able to discern how to work with the entire TGC API.
#!/usr/bin/env python3
"""The Game Crafter API client script."""
# Create a .env file in the same directory:
# TGC_API_KEY_ID=your_api_key_here
# TGC_USERNAME=your_username_here
# TGC_PASSWORD=your_password_here
# Install dependencies:
# pip install httpx python-dotenv
import os
import sys
from pathlib import Path
from typing import Any
import httpx
from dotenv import load_dotenv
def get_env_var(name: str) -> str:
"""Get a required environment variable or exit with error."""
value = os.getenv(name)
if not value:
print(f"Error: Missing required environment variable: {name}")
sys.exit(1)
return value
def create_session(client: httpx.Client, api_url: str, api_key_id: str, username: str, password: str) -> dict[str, Any]:
"""Authenticate and create a new session."""
response = client.post(
f"{api_url}/session",
params={"api_key_id": api_key_id, "username": username, "password": password},
)
response.raise_for_status()
return response.json()["result"]
def get_user_info(client: httpx.Client, api_url: str, session_id: str, user_id: str) -> dict[str, Any]:
"""Fetch user account information."""
response = client.get(
f"{api_url}/user/{user_id}",
params={"session_id": session_id},
)
response.raise_for_status()
return response.json()["result"]
def upload_file(
client: httpx.Client,
api_url: str,
session_id: str,
folder_id: str,
file_path: Path,
) -> dict[str, Any]:
"""Upload a file to a folder."""
with file_path.open("rb") as f:
response = client.post(
f"{api_url}/file",
params={
"name": file_path.name,
"folder_id": folder_id,
"session_id": session_id,
},
files={"file": (file_path.name, f, "application/octet-stream")},
)
response.raise_for_status()
return response.json()["result"]
def search_games(
client: httpx.Client,
api_url: str,
query: str,
session_id: str | None = None,
) -> list[dict[str, Any]]:
"""Search for games by query string."""
params: dict[str, str] = {"q": query}
if session_id:
params["session_id"] = session_id
response = client.get(f"{api_url}/game", params=params)
response.raise_for_status()
result = response.json()["result"]
return result.get("items", [])
def main() -> None:
"""Main entry point."""
load_dotenv()
api_url = "https://www.thegamecrafter.com/api"
api_key_id = get_env_var("TGC_API_KEY_ID")
username = get_env_var("TGC_USERNAME")
password = get_env_var("TGC_PASSWORD")
try:
with httpx.Client() as client:
# Get a session
print("--- Creating session ---")
session = create_session(client, api_url, api_key_id, username, password)
print(f"Session ID: {session['id']}")
print(f"User ID: {session['user_id']}")
print("------------------------")
# Fetch account info
print("--- Fetching account info ---")
user = get_user_info(client, api_url, session["id"], session["user_id"])
print(f"Username: {user.get('username')}")
print(f"Email: {user.get('email')}")
print("-----------------------------")
# Search for games
print("--- Searching games ---")
games = search_games(client, api_url, "Steampunk", session["id"])
print(f"Found {len(games)} results")
for game in games[:5]: # Show first 5
print(f" - {game.get('name')}")
print("-----------------------")
# Upload a file
root_folder_id = user.get("root_folder_id")
if root_folder_id:
print("--- Uploading file ---")
file_result = upload_file(
client, api_url, session["id"], root_folder_id, Path("example.png")
)
print(f"Uploaded: {file_result.get('name')}")
print("----------------------")
except httpx.HTTPStatusError as e:
print(f"HTTP error {e.response.status_code}: {e.response.text}")
sys.exit(1)
except httpx.RequestError as e:
print(f"Request error: {e}")
sys.exit(1)
except FileNotFoundError as e:
print(f"File not found: {e}")
sys.exit(1)
if __name__ == "__main__":
main()