Riot Games API Tutorials
  • Introduction
  • Part 1: What is the Riot Games API?
  • Part 2: Rate Limiting and Some Code!
  • Part 3
  • Appendix A: JSON
Powered by GitBook
On this page
  • Introduction
  • Rate Limiting: What is it and why is it important?
  • Code Time!
  • Explanation of the Code
  • Troubleshooting
  • Making it a True Backend
  • What's New?
  • Let's Try It
  • Passing Parameters to the Server
  • What's New?
  • Conclusion

Part 2: Rate Limiting and Some Code!

PreviousPart 1: What is the Riot Games API?NextPart 3

Last updated 6 years ago

Introduction

Welcome back to Part 2 of our 3-part series on First Steps with the Riot Games API. If you haven’t read through , I advise you to go through it before you read through Part 2. In Part 2, we will build on the foundations of by learning about Rate Limiting and then we will start programming and we will completely write the backend server code that will get data from the API and power our website!

Before we begin, make sure you have installed. This tutorial uses version 8.12, which is the current LTS version at the time of writing this. You may run into errors if you’re using a different version (or you may not). Go ahead and fire up your editor of choice for writing code (I personally use Visual Studio Code but you can use whatever you prefer). Before we start writing code, let’s cover a topic that is very important for understanding the API: Rate Limiting.

Rate Limiting: What is it and why is it important?

There are very large websites (op.gg) and there are very small websites (the one we’re about to make) that all use the Riot Games API. In order to ensure that everyone has fair access to the API, as well as to provide protection and stability for everyone, the Riot Games API enforces Rate Limits, which are simply restrictions on how many times you can request data from the API within a certain timeframe. Ok, now that I’ve taken a shot at explaining it in one sentence, go read Riot’s official documentation on the subject [link]. Note that it is fairly complex and quite a bit out of scope for this tutorial, but it is very important to understand that rate limits exist and that you’ll need to abide by them as you build out your own project.

It is important because if you consistently violate your rate limits (when you violate your rate limit you will get an error with the 429 error code) you risk getting your API key blacklisted, which means your key will no longer work with the API until you are removed from the blacklist (think of it as Riot changing the locks on the API so that your keys don’t work anymore).

NOTE: The code in this tutorial will NOT have any code that protects us against the rate limit. It is out-of-scope for this basic tutorial and I plan on covering it more in-depth in a future tutorial.

Code Time!

Now it is time to do some programming! Create a file called server.js, and insert the following code (make sure to fill in your own API Key between the quotes on Line 3):

server.js
const https = require('https');

const apiKey = 'REPLACE THIS WITH YOUR API KEY';
const url = 'https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/WxWatch?api_key=' + apiKey;

https.get(url, (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});

If your NodeJS is installed correctly and you've copied your API key where it says REPLACE THIS WITH YOUR API KEY, then if you run the command node server.js in the command prompt/shell of your choice, you should get a response similar to this:

{ id: 22511038,
  accountId: 36318904,
  name: 'WxWatch',
  profileIconId: 3019,
  revisionDate: 1538973413000,
  summonerLevel: 36 }

This should look familiar to what we observed in Part 1. The only difference is that instead of using our browser to fetch the data, we're using NodeJS to do it.

Explanation of the Code

Let's go over what each part of server.js does:

server.js
const https = require('https');

Here, we're simply requiring the https module built into NodeJS that we use to fetch the data from the API

server.js
const apiKey = 'REPLACE THIS WITH YOUR API KEY';
const url = 'https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/WxWatch?api_key=' + apiKey;

We're simply building the URL that we need to call the API by appending your API key to the URL.

server.js
https.get(url, (resp) => {
  let data = '';

  // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

  // The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });

}).on('error', (err) => {
  console.log('Error: ' + err.message);
});

This is where the API is actually being called. We use get() because the API requires us to use a GET request to fetch the data (as opposed to POST requests, which are generally used to send data TO a server, which is the opposite of what we are doing).

The get() method wants us to give it two things: the URL and a function that handles the response from the API. url is the URL we build above, and the rest of the code is the function that handles the response.

server.js
 // A chunk of data has been recieved.
  resp.on('data', (chunk) => {
    data += chunk;
  });

When the API returns us a chunk of data (sometimes it can't give us all the data at once, so it sends it in chunks), we add it onto the data that we already have (from the previous chunks).

server.js
// The whole response has been received. Print out the result.
  resp.on('end', () => {
    console.log(JSON.parse(data));
  });

When the API is done giving us chunks, it tells us that it is done (end) and then we can use console.log to print the data we've accumulated to the terminal where we ran the node server.js command. Since the API gives us JSON data, we use JSON.parse to make it into an object that we will be able to use later.

server.js
}).on('error', (err) => {
  console.log('Error: ' + err.message);
});

If we have any errors from the API, this will use console.log to print the error message to the terminal so we can see it.

Troubleshooting

{ status: { message: 'Unauthorized', status_code: 401 } }

This means that your API key is wrong or expired. Check and make sure your API key is properly inserted on line 3 and that it is not expired.

node not found / node not recognized as a cmdlet 

This means that NodeJS wasn't installed properly. Try reinstalling NodeJS or visit https://nodejs.org for assistance with your Node installation.

Making it a True Backend

Our program is great and all, but it only runs when you run the node server.js command and then it exits. This won't work if we're wanting it to wait until our website asks it for data. Let's alter our server.js file to listen for requests.

server.js
const https = require('https');
const http = require('http');

const apiKey = 'REPLACE THIS WITH YOUR API KEY';

const url = 'https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/WxWatch?api_key=' + apiKey;

const PORT = 8080;
const server = http.createServer((request, response) => {
    callAPI(response)
});

server.listen(PORT, () => console.log("Server is listening on port %s", PORT));

function callAPI(response) {
    https.get(url, (resp) => {
        let data = '';
        
        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });
        
        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            response.end(data);
        });
        
    }).on("error", (err) => {
        console.log("Error: " + err.message);
    });
}

What's New?

server.js
const http = require('http');

We need to require the http module for our server.

server.js
function callAPI(response) {
    https.get(url, (resp) => {
        let data = '';
        
        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });
        
        // The whole response has been received. Send it to the client.
        resp.on('end', () => {
            response.end(data);
        });
        
    }).on("error", (err) => {
        console.log("Error: " + err.message);
    });
}

We took our old https.get code and put it in a function that we called callAPI that requires a response object. We also changed the behavior when the entire API response has been received (line 12). Now, we call response.end(data) so that the server knows to pass the data back to the client that asks for it (this will be our browser shortly)

server.js
const PORT = 8080;
const server = http.createServer((request, response) => {
    callAPI(response)
});

server.listen(PORT, () => console.log("Server is listening on port %s", PORT));

This code is what actually makes the server that will listen for us to ask for data. Since this is a tutorial, the server will listen for http://localhost:8080 and will call the API when we go to that URL.

Let's Try It

Now that we've updated our server.js file, go ahead and run node server.js again. Notice that we no longer get the API data, instead it will print Server is listening on port 8080, which means it is waiting for us to go to http://localhost:8080 before it will do anything.

Now if you go to http://localhost:8080 in your browser, you should see the following:

{
"id": 22511038,
"accountId": 36318904,
"name": "WxWatch",
"profileIconId": 3019,
"revisionDate": 1538973413000,
"summonerLevel": 36
}

What is happening is that the server is waiting and once you hit the URL, it runs the code that we passed to it in http.createServer:

server.js
const server = http.createServer((request, response) => {
    callAPI(response)
});

In this case, it runs callAPI which we know will make the GET request to the API and then it gives the data back to the server which then gives it to your browser.

Passing Parameters to the Server

The final step in our backend server is to allow us to give it any summoner name we want and have it respond with the correct data. To do this, let's modify our server.js file one more time.

server.js
const https = require('https');
const http = require('http');
const url = require('url');

const apiKey = 'REPLACE THIS WITH YOUR API KEY';

const PORT = 8080;
const server = http.createServer((request, response) => {
    const parts = url.parse(request.url, true);
    const query = parts.query;
    const summonerName = query.summonerName;
    callAPI(summonerName, response)
});

server.listen(PORT, () => console.log("Server is listening on port %s", PORT));

function callAPI(summonerName, response) {
    const url = 'https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/' + summonerName + '?api_key=' + apiKey;

    https.get(url, (resp) => {
        let data = '';
        
        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });
        
        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            response.end(data);
            // console.log(JSON.parse(data));
        });
        
    }).on("error", (err) => {
        console.log("Error: " + err.message);
    });
}

What's New?

server.js
function callAPI(summonerName, response) {
    const url = 'https://na1.api.riotgames.com/lol/summoner/v3/summoners/by-name/' + summonerName + '?api_key=' + apiKey;

    https.get(url, (resp) => {
        let data = '';
        
        // A chunk of data has been recieved.
        resp.on('data', (chunk) => {
            data += chunk;
        });
        
        // The whole response has been received. Print out the result.
        resp.on('end', () => {
            response.end(data);
        });
        
    }).on("error", (err) => {
        console.log("Error: " + err.message);
    });
}

We added a summonerName parameter to callAPI and we have pulled the URL inside the function so that we can add the summonerName to the URL.

server.js
const url = require('url');

Again, we're simply importing the url module that we need.

server.js
const server = http.createServer((request, response) => {
    const parts = url.parse(request.url, true);
    const query = parts.query;
    const summonerName = query.summonerName;
    callAPI(summonerName, response)
});

Here, instead of just calling callAPI, which used to just get info for WxWatch, lines 2-4 are fetching the summonerName query parameter from the URL. In this case, instead of using http://localhost:8080 in the browser, we will need to tell it the summoner name by doing http://localhost:8080?summonerName=WxWatch

Now use the node server.js command to start your server and go to http://localhost:8080?summonerName=WxWatch in your browser. You should see the summoner information for WxWatch again:

{
"id": 585897,
"accountId": 31649572,
"name": "RiotSchmick",
"profileIconId": 746,
"revisionDate": 1538788984000,
"summonerLevel": 104
}

Now try changing WxWatch to any summoner name you'd like (caveat: they have to be in the NA region for now) and see what happens. (Hint: you should get the summoner info for that summoner)

Note if you use a summoner name with a space in it (e.g. Riot Schmick), you'll notice that your browser replaces the space with %20. This is called URL encoding and is out of scope for this tutorial. Just know that everything in a URL needs to be URL encoded or else it won't work (thankfully the browser takes care of this for the most part).

Conclusion

Now that we have a backend server capable of accepting URL requests with any summoner name, we are ready to build the actual website that will utilize this server. Join us in Part 3 where we will build this webpage using HTML and JavaScript!

Part 1
Part 1
NodeJS