text: Table of Contents
  Call of Duty is a first-person shooter video game franchise. Hundreds of millions of people have spent billions of hours playing the games. This is over the last couple of decades. My oldest son Kayin is the resident expert for online games at my house. He had one question when I spoke with him about Call of Duty. It was whether time spent playing correlated to success. Fortunately, there’s an API for that. In this article, we will walk through how to use the Call of Duty API with Python.
  Using this API, we will look for any correlation between time played and success. The metrics we will be tracking are the following. Score, experience points (xp), kill/death ratio (kdratio), level, and prestige. We will compare each of these to time played to look for positive correlations.
  The following list is a summary of the process we will follow:
  A Five-Step Process
  - Make sure you have python installed
  - Get an API Key
  - Use the Call of Duty API with Python
  - Chart the results to look for correlations
  Step 1. Make sure you have python installed
  For this article, we will be using a computer running Windows to run the Python code. I installed Python version 3 from the Python installation instructions for Windows.
  But to be sure, we will put up this sample code and try running it:
  #!/usr/bin/env python import sys sys.stdout.write("hello from Python %sn" % (sys.version,))
  When I save the code as hello.py and run this on my machine I see this:
  >python hello.py hello from Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]
  Python version 3.x is required to use the http.client library in the sample Python code for the Google News API.
  Step 2. Get an API Key
  Once we know Python is available, we need to get an API Key. The Call of Duty API we will be using is hosted on the RapidAPI platform. Getting a key is a simple process that is free. Go to the RapidAPI home page and use an email address or social media account to connect.
  Step 3. Subscribe to the Call of Duty API
  Once you register on the RapidAPI platform, the next step is to subscribe to the Call of Duty API. You can do that by clicking on the blue button on the endpoints page which says “Subscribe to Test”:
  After subscribing, we use the get Leaderboard endpoint. This is the only endpoint available which returns results for more than one gamer tag at a time. We will use that endpoint to gather metrics on several users for each platform.
  Step 4. Use the Call of Duty API with Python
  Now that we have made sure Python is available and subscribed to an API, it’s time to use it. First we will start with the sample code on the Endpoints page for Python http.client. This uses built in Python libraries (when you have Python version 3+ installed).
  import http.client conn = http.client.HTTPSConnection("call-of-duty-modern-warfare.p.rapidapi.com") headers = { 'x-rapidapi-host': "call-of-duty-modern-warfare.p.rapidapi.com", 'x-rapidapi-key': "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } conn.request("GET", "/leaderboard/1/psn", headers=headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
  You’ll need to replace the rapidapi-key Xs with your actual key. You will see this on the endpoints page when you are logged in.
  The sample code pulls user metrics in JSON format. Next, we will use Python to populate a local summary text file with the results. First we will loop through each platform, but only for psn, xbl, and battle. For steam the following message is returned:
  “Steam Doesn’t exist for MW. Try `battle` instead”.
  The other two options need an Activision ID or Tag so we’ll skip them for this exercise. But while testing the leaderboard endpoint I found a problem. For the three remaining platforms the metrics were identical in the first pages. So instead of trying to compare platforms we will pick one and pull more pages of results. Here is the full code to capture key metrics for 450 pages of the leaderboard from the battle platform:
  #! python """ File: captureCallOfDutyMetrics.py Description: This script pulls lists of users from the Call of Duty API. Then it loops through results to capture metrics for each user with time played above 10. The metrics for each user are saved into a csv file. """ #import libraries used below import http.client import json import time from pathlib import Path # This is where the captured statistics will be saved (in the local directory) # More information about the Path function is described at data_folder = Path("C:/Users/myUserName/Documents/") # Initialize counters timePlayed=0 kdRatio=0 score=0 xp=0 level=0 prestige=0 platforms = ['battle'] # Set to 1 to show details along the way for debugging purposes debug=0 numPagesToCapture=451 if debug>0: numPagesToCapture=5 #Loop through each platform for platform in platforms: thisFileName = "callOfDutyMetrics"+platform+".csv" outputFile = data_folder / thisFileName #start the file with a header outputCSV = "timePlayed,kdRatio,score,xp,level,prestige\n" #Loop through 450 pages per platform for page in range(numPagesToCapture): #there are no '0' pages in api results if page<1: continue print("about to pull page "+str(page)+" now\n") #Wait a second before every api call to keep within limit for this subscription level time.sleep(1) #Connect to the API conn = http.client.HTTPSConnection("call-of-duty-modern-warfare.p.rapidapi.com") headers = { 'x-rapidapi-host': "call-of-duty-modern-warfare.p.rapidapi.com", 'x-rapidapi-key': "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } conn.request("GET", "/leaderboard/"+str(page)+"/"+str(platform), headers=headers) res = conn.getresponse() data = res.read() # Load API response into a Python dictionary object, encoded as utf-8 string json_dictionary = json.loads(data.decode("utf-8")) #print(json_dictionary) # Loop through dictionary keys to access each entry for item in json_dictionary['entries']: # Pull the metrics for this player into a variable. thisMetrics = item['values'] timePlayed=thisMetrics['timePlayed'] if debug>0: print("timePlayed:"+str(timePlayed)+"\n") #print(thisMetrics) kdRatio=thisMetrics['kdRatio'] score=thisMetrics['score'] xp=thisMetrics['xp'] level=thisMetrics['level'] prestige=thisMetrics['prestige'] #Skip players who have played less than 10 hours if int(timePlayed)<10: continue #if debug>0: #print("Title:", thisTitle) # Create summary line for the csv file outputCSV+= str(timePlayed) + "," + str(kdRatio) + "," + str(score) + "," + str(xp) + "," + str(level) + "," + str(prestige) + "\n" #Now populate the csv file for this platform with open(outputFile, "w", encoding="utf-8") as f: f.write(outputCSV)
  Again, to use the code above you’ll need to replace the Xs with your RapidAPI Key. Also replace the path with a local path on your computer or server. What the code will do is to pull a list of gamer statistics from the first 450 pages of the leaderboard. This is from the “battle” platform. Then it loops through each entry retrieved. For each entry it pulls the metrics we want to compare into local variables. Finally it adds a row to a local Comma Separated Value (CSV) file.
  The query used in this example has 20 results for each of the API calls. This is for each page of the leaderboard. There are almost 4 million pages which can be queried for the battle platform. This means nearly 80 million player metrics can be retrieved.
  Step 5. Chart the results to look for correlations
  Using a one second delay between api requests, the script takes under ten minutes to complete. It retrieved nearly six thousand records. This is without including players who have played less than 10 hours. We charted several metrics against time played. Since they have different scales of data we need to look at them separately. This is how Experience Points (xp) correlates with Time Played:
  The time played is on the X-axis and Experience Points (XP) is on the Y-axis. There is a large variation but it does look like people gain about 5 million XP for every 2000 hours of time played. Next up is the ‘score’, where the correlation looks to be limited on the upside but not as much on the downside. Almost like there is a max score you can get based on how much time you have played. The max seems to be about 500,000 scores for every 1000 hours played:
  My son explained to me that prestige and level values are related somehow. But according to the data it looks like there is a max prestige level of 100:
  The one metric which doesn’t show a positive correlation with time played is the Kill/Death ratio. I figured maybe people would improve their ratio over time. But it looks like the initial wide variation simply levels out over time:
  Conclusion
  In this article, we have walked through an example of using the Call of Duty API with Python. We started by getting set up with the API and then used Python to create a CSV file with the results. Then we charted the results in several graphs using Excel.
  The thesis under test is whether success in the game goes up with the hours played. This question comes from my oldest son who is a gamer. He’s seen people who have dedicated large portions of their lives to games. Sometimes he wonders if that gives them an advantage.
  In the data we’ve captured, there is a strong correlation between time played and xp. This makes sense because the longer you play the more experience you gain. There is also a weaker correlation between time played and score. There are many people who have a steady increase compared to their time played. But others have played for thousands of hours with not much score to show for it. As expected, the levels generally increase with time played. But the kill/death ratio seems to converge over time around 1. This may be due to increased difficulty as you progress in games. The increased difficulty keeps up with the improved skill of the players. That is one way to keep people engaged over time.
  So is time played correlated to success? That depends on how you measure it. 🙂
  Hello, thank’s for your tutorial.
  How do you know that “timeplayed” is in hours?
  When I retrieve data for myself “timeplayed” is in seconds. That would possibly change your results.
  Thank you
  Hi John,
  When I look back at the charts it seems to me that some metrics are in hours and some are in seconds. Hours was an assumption since I did not see units mentioned and when spot checking I saw some low numbers in timeplayed with higher numbers in other fields. For example this is the first data point in the sample data response for the leaderboard:
  “rank”:1
  “rating”:0
  “updateTime”:26499
  “username”:”kinglinsjames#7665287″
  “values”:{20 items
  “accuracy”:0
  “assists”:0
  “averageTime”:15
  “deaths”:41
  “gamesPlayed”:0
  “headshots”:2
  “hits”:0
  “kdRatio”:0.2926829268292683
  “kills”:12
  “killstreak”:0
  “level”:3
  “losses”:0
  “misses”:0
  “prestige”:0
  “score”:0
  “scorePerMinute”:0
  “shots”:0
  “timePlayed”:15
  “wins”:15
  “xp”:9342
  }
  Can someone really be on level 3 with 15 wins and 41 deaths in 15 seconds or even minutes?
  There is a discussion page at where you can ask questions about how the fields are calculated.
  Are you on the leaderboard or did you use a different endpoint? I made no mention of the “rank” parameter because it did not seem to correlate with the other stats.
  Regards,
  Robert