Steam API Interaction
This guide demonstrates how to interact with the Steam Web API to fetch user data. It covers resolving vanity URLs (custom usernames) to Steam IDs, retrieving player profiles, and listing owned games with playtime stats.
Modules Used:
- requests: To make HTTP requests to the Steam API.
- python-dotenv: To securely manage the API key.
- argparse: To handle command-line arguments.
Prerequisites
- Steam Account: You need a Steam account.
- API Key: Get a free Steam Web API Key from steamcommunity.com/dev/apikey. You can use any domain name (e.g.,
localhost) if you don't have a website.
Installation
pip install requests python-dotenv
Setup
Create a .env file in your project directory:
STEAM_API_KEY=your_actual_api_key_here
The Code
Save this as steam_tool.py.
import requests
import os
import argparse
import sys
from dotenv import load_dotenv
# Load Config
load_dotenv()
API_KEY = os.getenv("STEAM_API_KEY")
BASE_URL = "http://api.steampowered.com"
def get_steam_id(vanity_url):
"""Resolves a Vanity URL (username) to a 64-bit Steam ID."""
# If it looks like a steam ID (digits, length 17), return it directly
if vanity_url.isdigit() and len(vanity_url) == 17:
return vanity_url
url = f"{BASE_URL}/ISteamUser/ResolveVanityURL/v0001/"
params = {'key': API_KEY, 'vanityurl': vanity_url}
try:
r = requests.get(url, params=params)
data = r.json()
if data['response']['success'] == 1:
return data['response']['steamid']
else:
return None
except Exception as e:
print(f"Error resolving URL: {e}")
return None
def get_player_summary(steam_id):
url = f"{BASE_URL}/ISteamUser/GetPlayerSummaries/v0002/"
params = {'key': API_KEY, 'steamids': steam_id}
r = requests.get(url, params=params)
data = r.json()
players = data['response']['players']
if players:
p = players[0]
print(f"\n--- Player: {p['personaname']} ---")
print(f"Steam ID: {p['steamid']}")
print(f"Profile URL: {p['profileurl']}")
status = "Online" if p.get('personastate') == 1 else "Offline"
print(f"Status: {status}")
if 'gameextrainfo' in p:
print(f"Playing: {p['gameextrainfo']}")
def get_owned_games(steam_id):
url = f"{BASE_URL}/IPlayerService/GetOwnedGames/v0001/"
params = {
'key': API_KEY,
'steamid': steam_id,
'include_appinfo': 1, # Include game names
'format': 'json'
}
r = requests.get(url, params=params)
data = r.json()
response = data.get('response', {})
game_count = response.get('game_count', 0)
games = response.get('games', [])
print(f"\nOwned Games: {game_count}")
# Sort by playtime (playtime_forever is in minutes)
games.sort(key=lambda x: x.get('playtime_forever', 0), reverse=True)
print("Top 5 Most Played:")
for g in games[:5]:
hours = g.get('playtime_forever', 0) / 60
print(f" - {g['name']}: {hours:.1f} hours")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Steam API Tool")
parser.add_argument("user", help="Steam Vanity URL name (e.g., 'gabelogannewell') or Steam ID 64")
args = parser.parse_args()
if not API_KEY:
print("Error: STEAM_API_KEY not found in .env")
sys.exit(1)
steam_id = get_steam_id(args.user)
if steam_id:
get_player_summary(steam_id)
get_owned_games(steam_id)
else:
print(f"User '{args.user}' not found.")
Usage
# Using a Vanity URL (Custom ID)
python steam_tool.py gabelogannewell
# Using a Steam ID 64 directly
python steam_tool.py 76561197960287930