Consuming an esports GraphQL API using JavaScript. | by Isak Höglund | GRID Esports

Consuming an esports GraphQL API using JavaScript.

If you are interested in building an esports application (from scratch), look no further!

In this article, we’ll look at consuming GraphQL only using JavaScript, while showing how you get access to an API to build and fuel your own esports application.

Here is a quick recap of the strengths of working with GraphQL.

Let’s try to create a simple website form with a search, that queries for esports teams based on the field input. We’ll use ES6 JavaScript, with some sprinkles of HTML5 and CSS3. This project won’t be using any libraries, to keep it as simple as possible and showcase that using GraphQL APIs are possible without adding a bunch of external dependencies.

Please note that this is a client side example and you would normally do the API request through a backend service to not expose your API key.

First, let’s acquire the API key that we will need to power the app.

You can apply for a key over here , by clicking “Apply for Early Access”.

The API itself is built by GRID Esports. At GRID, we strive to make in-game data accessible and easy to work with. Through our partnerships with tournaments and game publishers, we’re able to package and ship game data through our GraphQL APIs.

After you have gotten your key, let’s generate our project files. For our index.html, we’ll have it structured like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Esport Team Search</title>
    <meta charset="UTF-8" />
  </head>

<body>
    <div id="form-container">
      <form id="team-search">
        <input
          type="text"
          id="search"
          name="search"
          placeholder="Search for esport teams..."
          autocomplete="off"
        />
        <button type="submit">Enter</button>
      </form>
      <div id="team-container"></div>
    </div>
    <div id="app"></div>

<script src="src/index.js"></script>
  </body>
</html>

After adding some styling to the CSS, it looks something like this:

Now, let us start building out our index.js file. We can set up our event listener on the form to listen to our inputs:

const getSearchForm = () => {
  return document.querySelector("#team-search");
};

const getTeamsFromSearch = (ev) => {
  ev.preventDefault();
  const formInput = getSearchForm().elements["search"].value;
  console.log(formInput);
};

getSearchForm().addEventListener("submit", (e) => {
  getTeamsFromSearch(e);
});

Now that we see that the form inputs are logged in our browser console, we can continue with the more spicy part. Next, we’ll use the native JavaScript fetch() to query the GraphQL API.

We’re using a POST Method in our fetch, so a rough overview of the request will look something like this:

const fetchTeamsFromCentral = async (teamQuery) => {
  const request = await fetch("https://api-op.grid.gg/central-data/graphql", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY // Your API key
    },
    body: JSON.stringify({
      query: teamQuery // Your query paramaters variable
    })
  });

const response = await request.json();
  return response; // Returning the JSON response.
};

There are a few variables we need to account for to make this run properly. Those are:

  1. The URL endpoint will be set to https://api-op.grid.gg/central-data/graphql
  2. We need a valid API key, which we can input as a string in the header. Disclaimer: The API key in the above snippet would be exposed to users when executed client-side by the browser. Hence, if you are not working locally, save your API Key in a backend service (e.g. Node.js or Express.js) which can then make the actual API call with the API key and send the data back to your client.
  3. Our body query, in this case, called teamQuery. We will need to construct a query in the body of the fetch request that controls the data we’ll extract from the API.

The teamQuery variable with our body query will look like this:

const teamQuery = `
  query GetTeams {
    teams(filter: {name: {contains: "${formInput}"}}) {
      edges {
        node {
          name
        }
      }
    }
  }
`;

This query will look at the teams field in the GraphQL schema and filter the query based on the form input. Then we’re asking for the API to return us the names that contain the form input. So in short, based on what you put in the form field, we’ll get back a list of teams.

Let’s hook this up with our fetch and this will give us something looking like this:

const getSearchForm = () => {
  return document.querySelector("#team-search");
};

const getTeamContainerDiv = () => {
  return document.querySelector("#team-container");
};

const fetchTeamsFromCentral = async (teamQuery) => {
  const request = await fetch("https://api-op.grid.gg/central-data/graphql", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY
    },
    body: JSON.stringify({
      query: teamQuery
    })
  });

const response = await request.json();
  return response;
};

const getTeamsFromSearch = async (ev) => {
  ev.preventDefault();
  const keywordTeams = getSearchForm().elements["search"].value;

const teamQuery = `
    query GetTeams {
      teams(filter: {name: {contains: "${keywordTeams}"}}) {
        edges {
          node {
            id
            name
          }
        }
      }
    }
  `;

const teams = await fetchTeamsFromCentral(teamQuery);
  console.log(teams);
};

getSearchForm().addEventListener("submit", (e) => {
  getTeamsFromSearch(e);
});

Finally, we can:

  1. add a loop to render a list of the JSON results to our DOM in the getTeamsFromSearch function.
  2. clear our container that holds our divs when new search submits are entered.
  3. bake all of it together.

Then we end up with something like this:

const getSearchForm = () => {
  return document.querySelector("#team-search");
};

const getTeamContainerDiv = () => {
  return document.querySelector("#team-container");
};

const fetchTeamsFromCentral = async (teamQuery) => {
  const request = await fetch("https://api-op.grid.gg/central-data/graphql", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "x-api-key": API_KEY
    },
    body: JSON.stringify({
      query: teamQuery
    })
  });
  const response = await request.json();
  return response;
};

const clearTeamContainerDiv = () => {
  return (getTeamContainerDiv().innerHTML = "");
};

const getTeamsFromSearch = async (ev) => {
  ev.preventDefault();
  const keywordTeams = getSearchForm().elements["search"].value;
  const teamQuery = `
    query GetTeams {
      teams(filter: {name: {contains: "${keywordTeams}"}}) {
        edges {
          node {
            id
            name
          }
        }
      }
    }
  `;
  const teams = await fetchTeamsFromCentral(teamQuery);
  teams.data.teams.edges.forEach((team) => {
    const newDiv = document.createElement("div");
    const newContent = document.createTextNode(team.node.name);
    newDiv.appendChild(newContent);
    newDiv.classList.add("team-item");
    getTeamContainerDiv().appendChild(newDiv);
  });
};

getSearchForm().addEventListener("submit", (e) => {
  clearTeamContainerDiv();
  getTeamsFromSearch(e);
});

Ta-da, the final result:

A simple JavaScript app that allows us to communicate and consume a GraphQL database — without any libraries might I add.

If you have an idea about an application you want to build on top of any esports data, please feel free to apply to the Open Platform program and I’ll be happy to consult and help you get started!

Make sure to follow GRID on LinkedIn and Twitter for news and updates on esports and game data- and keep an eye out for future articles for help in building your esports applications!

Data