How to Use Repl Talk API/GraphQL [NODEJS]
h
RayhanADev (1871)

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!

You are viewing a single comment. View All
EpicGamer007 (1601)

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