Python – Chess.com raw stats snippet

I made a plugin for this in PHP, now I decided to make a snippet in Python. The snippet is made a bit different with no object filtering, just dictionary usage. This code can be enhanced greatly, this snippet is very simple in current form.

To make this work you will need to fill in a username from Chess.com, you can find a member at https://www.chess.com/members too.

import requests
import json

# Fill in the USERNAME below to make this work.
request = requests.get('https://api.chess.com/pub/player/USERNAME/stats')
# Print data if need to review json from chess.com print(data)
data = request.json()

# fide and lessons are defaulted to y which may be just be an int or incorrect
for x, y in data.items():
    # Lots of conditionals due to various formats games, lessons, ratings, best
    # Noticed if I use a 'or' in the elif for lessons or fide broke script
    if x == 'tactics':
        l = y['highest']['rating'] if y['highest']['rating'] else 'NA'
    elif x == 'lessons':
        l = y if y else '?'
    elif x == 'fide':
        l = y if y else '?'
    elif x == 'puzzle_rush':
        l = y['best']['score'] if y['best']['score'] else 'NA'
    else:
        # used bool to check if dictionary value exisit = True, a first
        l = y['last']['rating'] if bool(y['last']['rating']) else 'NA'
    print(x,l)
# Sample output
chess_bullet 2682
chess_blitz 2826
fide ?
tactics 3301
lessons ?
puzzle_rush 48

Leave a Comment