Example of Writing and Executing Queries

In this example, we’ve created a GraphQL query to get w3wiki course information from the GraphQL server. The server utilizes the resolver to retrieve and prepare the response. Following that, the server gave us a response. We have used the JavaScript fetch method to send a POST request with GraphQL query to server as client and to handle and display the response. The Node and Express server is used in the backend to execute the GraphQL query. It defines a GraphQL schema for courses, including title and price attributes. The server’s data source is an array of courses stored in memory. The GraphQL endpoint is set up at “/graphql”, and the server works on port 3000.

here is the step-by-step breakdown:

Step 1: We have created a HTML file that integrates the JavaScript (script.js) file. This HTML file contain a button to fetch the course details from the server.

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GraphQL Queries</title>
<style>
body {
font-family: 'Tahoma', Geneva, Verdana, sans-serif;
margin: 20px;
background-color: #f4f4f4;
text-align: center;
}

h1 {
color: #4CAF50;
}

h2 {
color: #333;
}

button {
background-color: #4CAF50;
color: white;
padding: 10px 20px;
font-size: 16px;
border: none;
cursor: pointer;
margin-top: 20px;
border-radius: 0.5rem;
transition: background-color 0.3s;
}

button:hover {
background-color: #45a049;
}

#result {
margin-top: 20px;
}

ul {
list-style: none;
padding: 0;
}

li {
background-color: #fff;
border: 1px solid #ddd;
margin: 5px auto;
padding: 10px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
width: 50%;
box-sizing: border-box;
}
</style>
</head>

<body>
<h1>w3wiki</h1>
<h2>Courses</h2>
<button onclick="fetchData()">Fetch Courses</button>
<div id="result"></div>
<script src="./script.js"></script>
</body>
</html>

Step 2: The script.js is our client, sending a POST request to GraphQL server or GraphQL endpoint, created using Node & Express with the defined GraphQL query.

// script.js
async function fetchData() {
try {
const response = await fetch('http://localhost:3000/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
query: `
query {
courses {
title
price
}
}
`,
}),
});

const data = await response.json();
displayData(data.data.courses);
} catch (error) {
console.error('Error fetching data:', error.message);
}
}

function displayData(courses) {
const resultContainer = document.getElementById('result');
resultContainer.innerHTML = '';

if (courses.length === 0) {
resultContainer.innerHTML = 'No courses found.';
return;
}

const ul = document.createElement('ul');
courses.forEach(course => {
const li = document.createElement('li');
li.textContent = `${course.title} by ${course.price}`;
ul.appendChild(li);
});

resultContainer.appendChild(ul);
}

Step 3: The query is to find all the courses with their title and corresponding price. The server.js file is working as a server, that receives the client’s POST request along with the query as the payload. The root level query resolver fetches the hardcorded courses array and then it is converted into required response JSON format.

// server.js - Node & Express Server
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
const cors = require('cors');

const coursesData = [
{ title: 'Master Java Programming - Complete Beginner to Advanced', price: '₹1999' },
{ title: 'Data Structures and Algorithms - Self Paced', price: '₹3999' },
];

// GraphQL schema
const schema = buildSchema(`
type Course {
title: String
price: String
}

type Query {
courses: [Course]
}
`);

// GraphQL root level resolver
const root = {
courses: () => coursesData,
};

// Express server
const app = express();

// Enable CORS
app.use(cors());

// GraphQL endpoint
app.use(
'/graphql',
graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
})
);

const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}/graphql`);
});

Step 4: This JSON response is sent to the client.

Course GrapQL query execution

Writing and Executing Queries in GraphQL

GraphQL has developed into an effective API language that offers developers more effective and adaptable ways to work with data. By enabling clients to request only the data they require, GraphQL, in contrast with traditional REST APIs, removes over- and under-conditioning. In this article, we are going to go through the fundamentals of creating and executing queries in GraphQL.

Similar Reads

Writing Queries in GraphQL

With GraphQL, developers may request just what data they require. You may customize queries to meet the needs of your application, in contrast to standard REST APIs where many endpoints provide fixed data formats....

Executing Queries in GraphQL

Are you familiar with GraphQL queries and their operation?...

Example of Writing and Executing Queries

In this example, we’ve created a GraphQL query to get geeksforgeeks course information from the GraphQL server. The server utilizes the resolver to retrieve and prepare the response. Following that, the server gave us a response. We have used the JavaScript fetch method to send a POST request with GraphQL query to server as client and to handle and display the response. The Node and Express server is used in the backend to execute the GraphQL query. It defines a GraphQL schema for courses, including title and price attributes. The server’s data source is an array of courses stored in memory. The GraphQL endpoint is set up at “/graphql”, and the server works on port 3000....

Conclusion

One of the features that defines GraphQL as a developer-friendly tool is its ability to customize queries to the specific needs of your application while keeping an easy execution process. Accept its efficiency and versatility, and watch as your queries flow smoothly with your data....

Contact Us