In case you are a gamer and an avid programmer too. You've come in the right spot. We will try to reproduce a 1$ version of the popular gaming stats site https://eune.op.gg/.
Along the way, in this article, you will learn how to create a custom API endpoint with Strapi. For the endpoint, a custom action will be defined too to be able to fetch external data. We will also enable the GraphQL plugin and allow the custom API endpoint to query through GraphQL with custom schema and resolvers.
You can download the backend here: Github repository, and we will integrate it with a NextJs frontend project to display our gaming statistics nicely.
As stated on the official GraphQL page, it is nothing more than a query language for APIs. GraphQL allows a client (frontend page) to retrieve only the data it needs from an API and nothing more, making it a faster and scalable way to power complex applications.
It was firstly developed by Facebook and became open-source in 2015.
Before starting on building the app, make sure that you already have a Riot Games account. If not, you can easily create one or use the social login button. You will need an account to be able to generate an API key on the dashboard page.
Once you have generated the key, make sure to store it in a .env
file so it is not publicly exposed inside the code, and keep it secret.
Now that everything is set up let's get our hands dirty and start on coding. The first thing you would want to do is pick an easy and accessible location to store our backend/frontend projects. Mine will reside under C:\Projects
.
Make sure to create the frontend and backend folders first.
For the backend part, let's begin with a simple Strapi quickstart application.
Open a terminal window and navigate under C:\Projects\backend
. Once in the desired location, run the following command:
yarn create strapi-app <name> --quickstart
It will create all the files and configurations needed to start coding once the project is created directly. The default database that will be used is SQLite.
As required, make sure to add the following packages after the installation is complete yarn add axios strapi-plugin-graphql
. The latter one will download and install the GraphQL plugin for your Strapi app.
Once you've created your admin profile and managed to log in to the admin page: http://localhost:1337/admin, the next thing we will be creating the custom API. To do so, we will be using the Strapi CLI capabilities, or you can do it manually if you prefer so.
Make sure that you are located under the root
directory of your backend project, and inside your terminal, run the following command:
strapi generate:api riot
For this article, I won't be needing the model's folder so you could delete it and all its content under .\backend\api\riot\models
. This way, it won't show up on the sidebar of the admin panel as we don't necessarily need it there for now.
Custom routes
Now let's start creating our custom route. Inside the following file .\api\riot\config\routes.json
, you can overwrite all the generated routes with the following code:
1 {
2 "routes": [
3 {
4 "method": "GET",
5 "path": "/summoner/:summoner",
6 "handler": "summoner.findSummonerByName",
7 "config": {
8 "policies": []
9 }
10 }
11 ]
12 }
Each time a request is sent to the endpoint localhost:1337\summoner\:summoner
, the controller handler action findSummonerByName
will be called.
Controller
Now let’s define our custom controller action. Make sure to copy the following bits of code inside .\api\riot\controllers\summoner.js
:
1 "use strict";
2 module.exports = {
3 findSummonerByName: async (ctx) => {
4 try {
5 const summoner = ctx.params.summoner || ctx.params._summoner;
6 const profile = await strapi.services.riot.summoner(summoner);
7 const games = await strapi.services.riot.games(profile.puuid);
8 return { ...profile, games: games };
9 } catch (err) {
10 return err;
11 }
12 },
13 };
Please take note that inside our controller, we're making use of two custom services. These services are created to fetch the required data from the Riot servers and return it to our API. You can also make use of them anywhere you want inside your Strapi application.
Services
Now let's take a look at our services code that is under .\api\riot\services\riot.js
1 const axios = require("axios");
2
3 const fetchRiot = async (uri) => {
4 const { data } = await axios.get(uri, {
5 headers: { "X-Riot-Token": process.env.RIOT_KEY },
6 });
7 return data;
8 };
9
10 module.exports = {
11 summoner: async (name) => {
12 // Setup e-mail data.
13 try {
14 const data = await fetchRiot(
15 `https://eun1.api.riotgames.com/lol/summoner/v4/summoners/by-name/${name}`
16 );
17 return data;
18 } catch (err) {
19 return err;
20 }
21 },
22 games: async (puuid) => {
23 try {
24 const data = await fetchRiot(
25 `https://europe.api.riotgames.com/lol/match/v5/matches/by-puuid/${puuid}/ids?start=0&count=5`
26 );
27 const games = await Promise.all(
28 data.map(async (id) => {
29 const {
30 info: {
31 gameCreation,
32 gameDuration,
33 gameId,
34 gameMode,
35 participants,
36 },
37 } = await fetchRiot(
38 `https://europe.api.riotgames.com/lol/match/v5/matches/${id}`
39 );
40 return {
41 gameCreation: gameCreation,
42 gameDuration: gameDuration,
43 gameId: gameId,
44 gameMode: gameMode,
45 ...participants.filter((item) => {
46 return item.puuid == puuid;
47 })[0],
48 };
49 })
50 );
51 return games;
52 } catch (err) {
53 return err;
54 }
55 },
56 };
GraphQL schema
The Strapi CLI does not automatically generate the following file that we will need, but you can manually create it with no worries.
So inside .\api\riot\config\schema.graphql.js
is the place where you will need to define the custom GraphQL schema for your custom routes. Make sure to have to following code pasted inside:
1 module.exports = {
2 definition: `
3 type Game {
4 gameCreation: Int!,
5 gameDuration: Int!,
6 gameId: Int!,
7 gameMode: String!,
8 assists: Int!,
9 kills: Int!,
10 deaths: Int!,
11 championName: String!,
12 champLevel: Int!
13 win: Boolean!
14 }
15
16 type Summoner {
17 id: String!,
18 accountId: String!,
19 puuid: String!,
20 name: String!,
21 profileIconId: Int!,
22 revisionDate: Int!,
23 summonerLevel: Int!,
24 games: [Game]
25 }`,
26 query: `
27 Summoner(summoner: String!): Summoner!
28 `,
29 resolver: {
30 Query: {
31 Summoner: {
32 description: "Get the Summoner object in the Riot API.",
33 resolver: "application::riot.summoner.findSummonerByName",
34 },
35 },
36 },
37 };
Now that everything is in place in your browser, you can navigate to the GraphQL interface: http://localhost:1337/graphql of your project and test the following query:
1 query SummonerByName($summoner: String!){
2 SummonerInfo: Summoner(summoner: $summoner ) {
3 id
4 puuid
5 name
6 summonerLevel
7 profileIconId
8 games {
9 gameMode
10 gameCreation
11 gameDuration
12 assists
13 kills
14 deaths
15 championName
16 champLevel
17 win
18 }
19 }
20 }
Make sure that you also set the summoner
variable with your account's summoner name
or any existing summoner name
if you prefer.
If you managed to follow along correctly, it should return all the requested data successfully.
Take note that for our custom GraphQL Types we only declared less fields than returned from our REST endpoint. That’s the power of GraphQL as it can return only the required fields as oppose to the REST endpoint that returns all the fields available. This way your frontend site won’t be loaded with unnecessary data.
Make sure that you also have a look over the Strapi documentation on customizing the GraphQL schema.
Awesome! Now that our backend is ready, let's jump straight into our frontend page.
For the frontend page, we will be using NextJs. You can start a new project by running the following command yarn create next-app <name>
under C:\Projects\frontend
, and it will automatically bootstrap all the files and configurations needed so you can start on coding.
After the installation is done, make sure to add the following dependencies that we will use through the application yarn add @apollo/react-hooks @emotion/react @emotion/styled apollo-boost axios graphql
.
Home page
We will be using the already generated structure for the home page to render our main part of the app.
As a first step, into .\frontend\pages\index.js
you can simply copy and paste the below code:
1 import Head from "next/head";
2 import Image from "next/image";
3 import styles from "../styles/Home.module.css";
4 import styled from "@emotion/styled";
5 import Query from "../components/Query";
6 import SUMMONER_QUERY from "../queries/summoner/summoner";
7
8 const Summoner = styled.div`
9 flex-direction: column;
10 p {
11 padding: 0;
12 margin: 0;
13 line-height: 1.5;
14 }
15 img {
16 margin-bottom: 10px;
17 border-radius: 50px 50px;
18 }
19 `;
20 const Container = styled.div`
21 display: flex;
22 justify-content: center;
23 padding-top: 35vh;
24 `;
25 const Stats = styled.div`
26 display: flex;
27 flex-direction: column;
28 justify-content: center;
29 align-items: center;
30 `;
31 export default function Home() {
32 return (
33 <div className={styles.container}>
34 <Head>
35 <title>Create Next App</title>
36 <meta name="description" content="Generated by create next app" />
37 <link rel="icon" href="/favicon.ico" />
38 </Head>
39 <Container>
40 <main className={styles.main}>
41 <Query query={SUMMONER_QUERY} summoner="TwistedPot">
42 {({ data: { SummonerInfo } }) => {
43 return (
44 <div>
45 <Summoner className={styles.grid}>
46 <img
47 src={`http://ddragon.leagueoflegends.com/cdn/11.15.1/img/profileicon/${SummonerInfo.profileIconId}.png`}
48 alt="Image"
49 height="100"
50 width="100"
51 />
52 <p>{SummonerInfo.name}</p>
53 <p>Level: {SummonerInfo.summonerLevel}</p>
54 </Summoner>
55 <div className={styles.grid}>
56 {SummonerInfo.games.map((game) => {
57 return (
58 <div className={styles.card} key={game.gameCreation}>
59 <Stats>
60 <div
61 style={{
62 display: "flex",
63 flexDirection: "row",
64 justifyContent: "center",
65 alignItems: "center",
66 }}
67 >
68 <img
69 src={`http://ddragon.leagueoflegends.com/cdn/11.15.1/img/champion/${game.championName}.png`}
70 alt="Image"
71 height="50"
72 width="50"
73 style={{
74 borderRadius: "50px 50px",
75 }}
76 />
77 <p
78 style={{
79 paddingLeft: "25px",
80 }}
81 >
82 {game.championName}
83 </p>
84 </div>
85 <div
86 style={{
87 display: "flex",
88 flexDirection: "row",
89 justifyContent: "center",
90 alignItems: "center",
91 padding: "10px 0px",
92 }}
93 >
94 <img
95 src={`http://ddragon.leagueoflegends.com/cdn/5.5.1/img/ui/score.png`}
96 alt="Image"
97 height="25"
98 width="25"
99 />
100 <p>
101 {game.kills +
102 "/" +
103 game.deaths +
104 "/" +
105 game.assists}
106 </p>
107 </div>
108 <div
109 style={{
110 display: "flex",
111 flexDirection: "column",
112 width: "100%",
113 }}
114 >
115 <p>Champion Level: {game.champLevel}</p>
116 <p>Mode: {game.gameMode}</p>
117 <p>
118 Duration:{" "}
119 {Math.round(game.gameDuration / 1000 / 60)}{" "}
120 minutes.
121 </p>
122 <p>Result: {game.win ? "Win" : "Lose"}</p>
123 </div>
124 </Stats>
125 </div>
126 );
127 })}
128 </div>
129 </div>
130 );
131 }}
132 </Query>
133 </main>
134 </Container>
135 <footer className={styles.footer}>
136 <a
137 href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
138 target="_blank"
139 rel="noopener noreferrer"
140 >
141 Powered by{" "}
142 <span className={styles.logo}>
143 <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
144 </span>
145 </a>
146 </footer>
147 </div>
148 );
149 }
If you try to run the project with yarn dev
, you will probably get some errors. That's because to continue, we will need to create a couple more things.
Query component
The first thing is to create a reusable Query component that we can use anywhere in our code to fetch the \graphql
endpoint. The inspiration for the Query component was drawn from this blog post.
So Maxime deserves all the credits that I could stay DRY.
Make sure to have the following file created .\frontend\components\Query\index.js
1 import React from "react";
2 import { useQuery } from "@apollo/react-hooks";
3 const Query = ({ children, query, summoner }) => {
4 const { data, loading, error } = useQuery(query, {
5 variables: { summoner: summoner },
6 });
7 if (loading) return <p>Loading...</p>;
8 if (error) return <p>Error: {JSON.stringify(error.message)}</p>;
9 return children({ data });
10 };
11 export default Query;
It has been slightly modified so that it matched our needs.
The Query
The second thing that we will be needed is the actual query that we will use inside the Query component. You can use the GraphQL Interface that is available under http:\localhost:1337\graphql to build the query.
For the query, make sure to create the following file .\frontend\queries\summoner\summoner.js
1 import gql from "graphql-tag";
2 const SUMMONER_QUERY = gql`
3 query SummonerByName($summoner: String!) {
4 SummonerInfo: Summoner(summoner: $summoner) {
5 id
6 puuid
7 name
8 summonerLevel
9 profileIconId
10 games {
11 gameMode
12 gameCreation
13 gameDuration
14 assists
15 kills
16 deaths
17 championName
18 champLevel
19 win
20 }
21 }
22 }
23 `;
24 export default SUMMONER_QUERY;
Your final site should look more or less like so:
The source code for this article can be found below:
Congratulations for making it this far!
By the end of this tutorial, you should understand how to easily create custom routes to access external data and create a custom GraphQL schema for your routes to match your business logic.
Cretu is working as data processor and is interested in Python, Web Development, Data analysis.