Danblog

Medical Resident, Software Developer, Basketball Fan

A python library for xmlstats


xmlstats 1.0.0

xmlstats is a nice little (free) API for getting NBA and MLB stats. I've used the API in several Django projects, mostly for pulling box score data. The value of xmlstats is its ease of use and consistency. While you can get more interesting data using something like nickb1080/nba or some other library that utilizes stats.nba.com, the NBA Stats API is undocumented, quirky, and libraries relying on it will break not infrequently. xmlstats is more limited in what it can do, but if it fits your needs, it works well. Probably the biggest downside is the 6 requests per minute limit, a dealbreaker if you have any need for near realtime or frequent updates.

I wrote xmlstat-py to make it easier to get up and running with xmlstats, and just recently reworked and expanded the project (now covers all endpoints). My aim in the redesign for this simple wrapper was to stick closely to the underlying API. To that end, the Xmlstats class exposes methods that correspond with each endpoint provided by the API.

Install with pip: pip install xmlstats-py

To use, just instantiate the class using your access token and user agent:

s = Xmlstats(MY_ACCESS_TOKEN, MY_USER_AGENT)

Then call the method that corresponds to you're endpoint. Provide any API URL arguments or query parameters, just as they are documented in the xmlstats documentation, as parameters to the method. If they're optional, they don't have to be included.

data = s.nba_box_score(event_id="20120621-oklahoma-city-thunder-at-miami-heat")

The returned data is represented using a namedtuple, with a structure mirroring the JSON response provided by the API. A simple custom object_hook is used when loading the JSON, converting each object encountered into another namedtuple using the object keys as field names. This allows for nicer data access using dot notation as compared to previous versions of xmlstats-py. Continuing with the above example:

durant_points = [player.points for player in data.away_stats if player.last_name == 'Durant'][0]
# >>> 32

Source Code