1
+ """# MLB-StatsAPI
2
+
3
+ Python wrapper for MLB Stats API
4
+
5
+ Created by Todd Roberts
6
+
7
+ https://pypi.org/project/MLB-StatsAPI/
8
+
9
+ https://github.com/toddrob99/MLB-StatsAPI
10
+ """
1
11
# encoding=utf-8
2
12
import sys
3
13
if sys .version_info .major < 3 :
4
14
reload (sys )
5
15
sys .setdefaultencoding ('utf8' )
6
- """ Trying to support Python 2.7"""
16
+ # Trying to support Python 2.7
7
17
8
18
from . import version
9
19
__version__ = version .VERSION
@@ -243,11 +253,12 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
243
253
For example, to retrieve only the batting box: statsapi.boxscore(565997,battingInfo=False,fieldingInfo=False,pitchingBox=False,gameInfo=False)
244
254
"""
245
255
246
- """rowLen is the total width of each side of the box score, excluding the " | " separator; fullRowLen is the full table length"""
247
256
rowLen = 79
257
+ """rowLen is the total width of each side of the box score, excluding the " | " separator"""
248
258
fullRowLen = rowLen * 2 + 3
249
- """boxscore will hold the string to be returned """
259
+ """fullRowLen is the full table width """
250
260
boxscore = ''
261
+ """boxscore will hold the string to be returned"""
251
262
params = {'gamePk' :gamePk ,'fields' :'gameData,teams,teamName,shortName,teamStats,batting,atBats,runs,hits,rbi,strikeOuts,baseOnBalls,leftOnBase,pitching,inningsPitched,earnedRuns,homeRuns,players,boxscoreName,liveData,boxscore,teams,players,id,fullName,allPositions,abbreviation,seasonStats,batting,avg,ops,era,battingOrder,info,title,fieldList,note,label,value' }
252
263
if timecode : params .update ({'timecode' :timecode })
253
264
r = get ('game' ,params )
@@ -258,7 +269,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
258
269
home = r ['liveData' ]['boxscore' ]['teams' ]['home' ]
259
270
260
271
if battingBox :
261
- """ Add away column headers"""
272
+ # Add away column headers
262
273
awayBatters = [{'namefield' :teamInfo ['away' ]['teamName' ] + ' Batters' , 'ab' :'AB' , 'r' :'R' , 'h' :'H' , 'rbi' :'RBI' , 'bb' :'BB' , 'k' :'K' , 'lob' :'LOB' , 'avg' :'AVG' , 'ops' :'OPS' }]
263
274
for batterId_int in [x for x in away ['batters' ] if away ['players' ]['ID' + str (x )].get ('battingOrder' )]:
264
275
batterId = str (batterId_int )
@@ -279,7 +290,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
279
290
}
280
291
awayBatters .append (batter )
281
292
282
- """ Get away team totals"""
293
+ # Get away team totals
283
294
awayBatters .append ({
284
295
'namefield' :'Totals' ,
285
296
'ab' :str (away ['teamStats' ]['batting' ]['atBats' ]),
@@ -293,7 +304,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
293
304
'ops' :''
294
305
})
295
306
296
- """ Add home column headers"""
307
+ # Add home column headers
297
308
homeBatters = [{'namefield' :teamInfo ['home' ]['teamName' ] + ' Batters' , 'ab' :'AB' , 'r' :'R' , 'h' :'H' , 'rbi' :'RBI' , 'bb' :'BB' , 'k' :'K' , 'lob' :'LOB' , 'avg' :'AVG' , 'ops' :'OPS' }]
298
309
for batterId_int in [x for x in home ['batters' ] if home ['players' ]['ID' + str (x )].get ('battingOrder' )]:
299
310
batterId = str (batterId_int )
@@ -314,7 +325,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
314
325
}
315
326
homeBatters .append (batter )
316
327
317
- """ Get home team totals"""
328
+ # Get home team totals
318
329
homeBatters .append ({
319
330
'namefield' :'Totals' ,
320
331
'ab' :str (home ['teamStats' ]['batting' ]['atBats' ]),
@@ -328,13 +339,13 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
328
339
'ops' :''
329
340
})
330
341
331
- """ Make sure the home and away batter lists are the same length"""
342
+ # Make sure the home and away batter lists are the same length
332
343
while len (awayBatters ) > len (homeBatters ):
333
344
homeBatters .append ({'namefield' :'' ,'ab' :'' ,'r' :'' ,'h' :'' ,'rbi' :'' ,'bb' :'' ,'k' :'' ,'lob' :'' ,'avg' :'' ,'ops' :'' })
334
345
while len (awayBatters ) < len (homeBatters ):
335
346
awayBatters .append ({'namefield' :'' ,'ab' :'' ,'r' :'' ,'h' :'' ,'rbi' :'' ,'bb' :'' ,'k' :'' ,'lob' :'' ,'avg' :'' ,'ops' :'' })
336
347
337
- """ Build the batting box!"""
348
+ # Build the batting box!
338
349
for i in range (0 ,len (awayBatters )):
339
350
if i == 0 or i == len (awayBatters )- 1 :
340
351
boxscore += '-' * rowLen + ' | ' + '-' * rowLen + '\n '
@@ -343,7 +354,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
343
354
if i == 0 or i == len (awayBatters )- 1 :
344
355
boxscore += '-' * rowLen + ' | ' + '-' * rowLen + '\n '
345
356
346
- """ Get batting notes"""
357
+ # Get batting notes
347
358
awayBattingNotes = {}
348
359
for n in away ['note' ]:
349
360
awayBattingNotes .update ({len (awayBattingNotes ) : n ['label' ] + '-' + n ['value' ]})
@@ -362,7 +373,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
362
373
363
374
boxscore += ' ' * rowLen + ' | ' + ' ' * rowLen + '\n '
364
375
365
- """ Get batting and fielding info"""
376
+ # Get batting and fielding info
366
377
awayBoxInfo = {}
367
378
homeBoxInfo = {}
368
379
for infoType in ['BATTING' ,'FIELDING' ]:
@@ -419,16 +430,16 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
419
430
while len (awayBoxInfo ) < len (homeBoxInfo ):
420
431
awayBoxInfo .update ({len (awayBoxInfo ) : '' })
421
432
422
- """ Build info box"""
433
+ # Build info box
423
434
for i in range (0 ,len (awayBoxInfo )):
424
435
boxscore += ('{:<%s} | ' % rowLen ).format (awayBoxInfo [i ])
425
436
boxscore += ('{:<%s}\n ' % rowLen ).format (homeBoxInfo [i ])
426
437
if i == len (awayBoxInfo )- 1 :
427
438
boxscore += '-' * rowLen + ' | ' + '-' * rowLen + '\n '
428
439
429
- """ Get pitching box"""
440
+ # Get pitching box
430
441
if pitchingBox :
431
- """ Add away column headers"""
442
+ # Add away column headers
432
443
awayPitchers = [{'namefield' :teamInfo ['away' ]['teamName' ] + ' Pitchers' , 'ip' :'IP' , 'h' :'H' , 'r' :'R' , 'er' :'ER' , 'bb' :'BB' , 'k' :'K' , 'hr' :'HR' , 'era' :'ERA' }]
433
444
for pitcherId_int in away ['pitchers' ]:
434
445
pitcherId = str (pitcherId_int )
@@ -447,7 +458,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
447
458
}
448
459
awayPitchers .append (pitcher )
449
460
450
- """ Get away team totals"""
461
+ # Get away team totals
451
462
awayPitchers .append ({
452
463
'namefield' :'Totals' ,
453
464
'ip' :str (away ['teamStats' ]['pitching' ]['inningsPitched' ]),
@@ -460,7 +471,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
460
471
'era' :''
461
472
})
462
473
463
- """ Add home column headers"""
474
+ # Add home column headers
464
475
homePitchers = [{'namefield' :teamInfo ['home' ]['teamName' ] + ' Pitchers' , 'ip' :'IP' , 'h' :'H' , 'r' :'R' , 'er' :'ER' , 'bb' :'BB' , 'k' :'K' , 'hr' :'HR' , 'era' :'ERA' }]
465
476
for pitcherId_int in home ['pitchers' ]:
466
477
pitcherId = str (pitcherId_int )
@@ -479,7 +490,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
479
490
}
480
491
homePitchers .append (pitcher )
481
492
482
- """ Get home team totals"""
493
+ # Get home team totals
483
494
homePitchers .append ({
484
495
'namefield' :'Totals' ,
485
496
'ip' :str (home ['teamStats' ]['pitching' ]['inningsPitched' ]),
@@ -492,13 +503,13 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
492
503
'era' :''
493
504
})
494
505
495
- """ Make sure the home and away pitcher lists are the same length"""
506
+ # Make sure the home and away pitcher lists are the same length
496
507
while len (awayPitchers ) > len (homePitchers ):
497
508
homePitchers .append ({'namefield' :'' ,'ip' :'' ,'h' :'' ,'r' :'' ,'er' :'' ,'bb' :'' ,'k' :'' ,'hr' :'' ,'era' :'' })
498
509
while len (awayPitchers ) < len (homePitchers ):
499
510
awayPitchers .append ({'namefield' :'' ,'ip' :'' ,'h' :'' ,'r' :'' ,'er' :'' ,'bb' :'' ,'k' :'' ,'hr' :'' ,'era' :'' })
500
511
501
- """ Build the pitching box!"""
512
+ # Build the pitching box!
502
513
for i in range (0 ,len (awayPitchers )):
503
514
if i == 0 or i == len (awayPitchers )- 1 :
504
515
boxscore += '-' * rowLen + ' | ' + '-' * rowLen + '\n '
@@ -507,7 +518,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
507
518
if i == 0 or i == len (awayPitchers )- 1 :
508
519
boxscore += '-' * rowLen + ' | ' + '-' * rowLen + '\n '
509
520
510
- """ Get game info"""
521
+ # Get game info
511
522
if gameInfo :
512
523
z = r ['liveData' ]['boxscore' ].get ('info' ,[])
513
524
gameBoxInfo = {}
@@ -530,7 +541,7 @@ def boxscore(gamePk,battingBox=True,battingInfo=True,fieldingInfo=True,pitchingB
530
541
else :
531
542
gameBoxInfo .update ({len (gameBoxInfo ): x ['label' ] + (': ' if x .get ('value' ) else '' ) + x .get ('value' ,'' ) })
532
543
533
- """ Build the game info box"""
544
+ # Build the game info box
534
545
for i in range (0 ,len (gameBoxInfo )):
535
546
boxscore += ('{:<%s}' % fullRowLen + '\n ' ).format (gameBoxInfo [i ])
536
547
if i == len (gameBoxInfo )- 1 :
@@ -599,7 +610,7 @@ def linescore(gamePk,timecode=None):
599
610
str (r ['liveData' ]['linescore' ].get ('teams' ,{}).get ('home' ,{}).get ('errors' ,0 ))
600
611
])
601
612
602
- """ Build the linescore"""
613
+ # Build the linescore
603
614
for k in [[header_name ,header_row ],[away_name ,away ],[home_name ,home ]]:
604
615
linescore += ('{:<%s}' % str (len (max ([header_name ,away_name ,home_name ],key = len )) + 1 )).format (k [0 ])
605
616
linescore += ('{:^2}' * (len (k [1 ])- 3 )).format (* k [1 ])
@@ -786,7 +797,7 @@ def get(endpoint,params,force=False):
786
797
return value will be the raw response from MLB Stats API in json format
787
798
"""
788
799
789
- """ Lookup endpoint from input parameter"""
800
+ # Lookup endpoint from input parameter
790
801
ep = ENDPOINTS .get (endpoint )
791
802
if not ep : raise ValueError ('Invalid endpoint (' + str (endpoint )+ ').' )
792
803
url = ep ['url' ]
@@ -795,7 +806,7 @@ def get(endpoint,params,force=False):
795
806
path_params = {}
796
807
query_params = {}
797
808
798
- """ Parse parameters into path and query parameters, and discard invalid parameters"""
809
+ # Parse parameters into path and query parameters, and discard invalid parameters
799
810
for p ,pv in params .items ():
800
811
if ep ['path_params' ].get (p ):
801
812
if DEBUG : print ("Found path param:" ,p ) #debug
@@ -819,7 +830,7 @@ def get(endpoint,params,force=False):
819
830
if DEBUG : print ("path_params:" ,path_params ) #debug
820
831
if DEBUG : print ("query_params:" ,query_params ) #debug
821
832
822
- """ Replace path parameters with their values"""
833
+ # Replace path parameters with their values
823
834
for k ,v in path_params .items ():
824
835
if DEBUG : print ("Replacing {%s}" % k ) #debug
825
836
url = url .replace ('{' + k + '}' ,v )
@@ -839,15 +850,15 @@ def get(endpoint,params,force=False):
839
850
if DEBUG : print ("Removing optional param {%s}" % param ) #debug
840
851
url = url .replace ('{' + param + '}' ,'' )
841
852
if DEBUG : print ("URL:" ,url ) #debug
842
- """ Add query parameters to the URL"""
853
+ # Add query parameters to the URL
843
854
if len (query_params ) > 0 :
844
855
for k ,v in query_params .items ():
845
856
if DEBUG : print ("Adding query parameter %s=%s" % (k ,v ))
846
857
sep = '?' if url .find ('?' ) == - 1 else '&'
847
858
url += sep + k + "=" + v
848
859
if DEBUG : print ("URL:" ,url ) #debug
849
860
850
- """ Make sure required parameters are present"""
861
+ # Make sure required parameters are present
851
862
satisfied = False
852
863
missing_params = []
853
864
for x in ep .get ('required_params' ,[]):
@@ -863,7 +874,7 @@ def get(endpoint,params,force=False):
863
874
else : note = ''
864
875
raise ValueError ("Missing required parameter(s): " + ', ' .join (missing_params ) + ".\n --Required parameters for the " + endpoint + " endpoint: " + str (ep .get ('required_params' ,[])) + ". \n --Note: If there are multiple sets in the required parameter list, you can choose any of the sets." + note )
865
876
866
- """ Make the request"""
877
+ # Make the request
867
878
r = requests .get (url )
868
879
if r .status_code not in [200 ,201 ]:
869
880
raise ValueError ('Request failed. Status Code: ' + str (r .status_code ) + '.' )
0 commit comments