Skip to content
← Back to Community
How to Use Repl Talk API/GraphQL [NODEJS]
Profile icon
hacker
has Hacker Plan
RayhanADev

How to Use Repl.it's GraphQL/API

A NodeJS Tutorial

G'day fellow Repler's, today you will be learning how to use Repl.it's GraphQL! This easy to use API will grant you access to a whole lot of information and can make your projects super unique!

Background Information

What is GraphQL?

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

~ GraphQL Website

wtf does that mean?

~ tsunami21

Put simply you can query (sending a fetch request) a site's GraphQL and recieve information based on data you give!
In the context of Repl.it, one thing you can do is send a request to get user data, and then with the information you recieve, you can choose what you need for your project (such as the user's profile picture, or their cycles).

What Language Should I Use?

In this tutorial I will teach you how to use GraphQL with NodeJS, but I will release a Python tutorial shortly! NodeJS is a Javascript runtime environment typically used for backend development. We will use the 'node-fetch' module to make requests to the GraphQL.

Step #1: Create a Repl.

You can either use this template and skip to Step #3 or go ahead and create a new NodeJS Repl project and follow Step #2.

Step #2: Write Some Code.

If you are making a new project, start by requiring the necessary dependecies:

const fetch = require('node-fetch');

Afterwards, create a new variable called headers. This is where we will store our request headers, which give the GraphQL important information to function.

const headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', 'Accept-Encoding': 'gzip, deflate, br', 'Connection': 'keep-alive', 'X-Requested-With': 'Repl.it', 'Referrer': 'https://repl.it', 'Origin': 'https://repl.it' };

Now let's get into the real fun! Let's create an async function to query GraphQL and log that data.
Start by creating the function:

async function getData() { };

We want the function to accept a username parameter:

async function getData(username) { };

Now, we create a request to https://repl.it/graphql! We want to store the information from the request in a variable so that we can call the data later.

async function getData(username) { // The variable 'info' stores the information from the request let info = await fetch('https://repl.it/graphql', { // We POST the data in our request to the page method: 'POST', // The headers variable we created before headers, // The body, this is where our query to GraphQL is body: JSON.stringify({ query: `{userByUsername(username: "${username}") {karma, firstName, lastName, bio, isVerified, timeCreated, isLoggedIn, organization {name}, subscription {planId}, roles { name }}}` }); }); };

We want to keep the information in a neat format, so let's format it into JSON once we recieve it.

async function getData(username) { let info = await fetch('https://repl.it/graphql', { method: 'POST', headers, body: JSON.stringify({ query: `{userByUsername(username: "${username}") {karma, firstName, lastName, bio, isVerified, timeCreated, isLoggedIn, organization {name}, subscription {planId}, roles { name }}}` }).then(res => res.json()); // Convert our response from GraphQL into JSON format }); };

Last but not least, let's log the data that we get:

async function getData(username) { let info = await fetch('https://repl.it/graphql', { method: 'POST', headers, body: JSON.stringify({ query: `{userByUsername(username: "${username}") {karma, firstName, lastName, bio, isVerified, timeCreated, isLoggedIn, organization {name}, subscription {planId}, roles { name }}}` }).then(res => res.json()); }); // Log the data. Be sure to add '.data.userByUsername' to 'info' so that unneccesary stuff isn't visible console.log(info.data.userByUsername); };

Awesome! Give yourself a pat on the back because you just created a neat little program that will query GraphQL. To use it, simply call getData('username') at the end of the program. But why stop there?

Step 3: Use The Code.

Let's write a basic program using what we have to search up user's information!

Using what we created, lets add some dependecies:

// Easier console colors const colors = require('colors/safe'); // NodeJS Console IO const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout });

Now we are ready! Start by creating a new function to get user input:

function main() { };

Setup a readline question:

function main() { // readline.question creates a prompt (similar to input in Python!) // You can also use console colors like I did here to make it stand out readline.question(colors.yellow(`Username? \n`), (input) => { getData(input); //Our getData function from before, but now we use the input from console }); };

Now let's go to our getData function and make it the output look good:

async function getData(username) { let info = await fetch('https://repl.it/graphql', { method: 'POST', headers, body: JSON.stringify({ query: `{userByUsername(username: "${username}") {karma, firstName, lastName, bio, isVerified, timeCreated, isLoggedIn, organization {name}, subscription {planId}, roles { name }}}` }) }).then(res => res.json()); console.log('\n---------') // Add a spacer console.log(`${username}'s Data:`) // Display the user you searched console.log(info.data.userByUsername) // Log the data console.log('--------- \n') // Add a spacer main(); // Run the main function again when complete };

Tada, now change the getData('username') function that you called at the end of the program to be main() and you have completed your first project with GraphQL! Try searching a user's name and get their GraphQL info!

This tutorial (hopefully) taught you several of basics when using Repl.it's GraphQL, and there are much more advanced concepts, such as the amount of upvotes a post has all the way to displaying the hot posts in a board. Let me know below if you are interested in learning any! Good luck, and for everyone who uses Python a tutorial is coming for you too!

The Authors

Main Author: Rayhan ~

@RayhanADev

Emotional Support: Tsunami ~
@tsunami21

Link to Repl.it's GraphQL Playground: https://repl.it/graphql

Thanks for reading, and have a good day!

Voters
Profile icon
nuxtli
Profile icon
darkdarcool
Profile icon
frissyn
Profile icon
chillcafe
Profile icon
TsunamiOrSumth
Profile icon
Squirrel777
Profile icon
programmeruser
Profile icon
EpicGamer007
Profile icon
elipie
Profile icon
RayhanADev
Comments
hotnewtop
Profile icon
RahulChoubey1

Why do you use JSON.stringify and then use .then? What's the significance of the .then?

Profile icon
ApoorvAgrawal

Nice

Profile icon
programmeruser

This is more of "how to use fetch" than "how to create graphql queries and send them to the server."

Profile icon
RayhanADev

@programmeruser
okayokay someone already made the joke. I also don’t think I can say every single GQL query (even though I found them all today :DD).

Profile icon
programmeruser

@RayhanADev
you could learn how to do anything with repl.it's graphql api by using the network panel in devtools...

Profile icon
RayhanADev

@programmeruser
wdym?
also I have all the queries xD

Profile icon
programmeruser

@RayhanADev
don't mind this, just inspecting network...

Profile icon
programmeruser

@RayhanADev
I figured out how to make comments with graphql.

Profile icon
adsarebbbad

"karma"

Profile icon
RayhanADev

@adsarebbbad
yep. The Repl Devs seem to have a limitless sense of humor xD.

Profile icon
EpicGamer007

Can I try making this repl with HTML, CSS, and JS?

Cool tutorial too!

Profile icon
RayhanADev

@EpicGamer007
thank you! It is possible if you use the fetch() method. I can make a tutorial for HTML CSS and JS after Python if you would like?

Profile icon
EpicGamer007

@RayhanADev
huh wut do u mean? i was thinking of creating a node repl then using requests to display the info on the screen.

Profile icon
RayhanADev

@EpicGamer007
ohhhhhh, I thought you meant on BrowserJS, yeah you can do it like that with client-server communication (Sockets works ig?) I like using GET and POST, but you can use socket.io!

Profile icon
EpicGamer007

@RayhanADev
i wanna try using get and post, seems much safer

Profile icon
RayhanADev

@EpicGamer007
awesome!

Profile icon
programmeruser

@RayhanADev
you can't use socket.io to make HTTP requests.

Profile icon
RayhanADev

@programmeruser
not to make requests to communicate between client and server ;P.

Profile icon
RayhanADev

@elipie
Tutorial Jam Submission!

Profile icon
RayhanADev

Nice and sweet tutorial to teach everyone about Repl Talk’s GraphQL API! Enjoy!