MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
GraphQL Queries, Mutations & Subscriptions0%
Study Materials
JavaScript for AdvancedProgress 0%
1.1Higher-Order Functions & Currying1.2Function Composition & Pipelining1.3Memoization & Pure Functions1.4Execution Context & Call Stack Deep Dive1.5Scope Chain & Lexical Environment
11.1WebSockets for Real-Time Bidirectional Communication11.2Server-Sent Events (SSE)11.3Fetch Interceptors & Request Middleware11.4GraphQL Queries, Mutations & Subscriptions
HomeTutorialsJavaScript for AdvancedGraphQL Queries, Mutations & Subscriptions
JSON.stringify Replacer & JSON.parse Reviver

GraphQL Queries, Mutations & Subscriptions

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study Materials

While REST APIs require multiple round-trips to disparate endpoints (/users/1, /users/1/orders, /users/1/posts) leading to over-fetching or under-fetching, GraphQL allows clients to request exactly the data they need in a single query.


1. The Three Operations of GraphQL

  1. 1
    Query: Read-only data retrieval (analogue to HTTP GET).
  2. 2
    Mutation: Data writes, updates, and deletes (analogue to POST, PUT, DELETE).
  3. 3
    Subscription: Real-time event streams powered by WebSockets.

2. Executing Queries with Native Fetch

GraphQL does not require heavy client libraries (like Apollo Client) for basic needs. All queries execute as standard HTTP POST requests to a single /graphql endpoint:

1async function fetchUserProfile(userId) {
2 const query = `
3 query GetUserWithOrders($id: ID!) {
4 user(id: $id) {
5 id
6 name
7 email
8 orders(limit: 3) {
9 id
10 totalAmount
11 status
12 }
13 }
14 }
15 `;
16 
17 const response = await fetch('https://api.example.com/graphql', {
18 method: 'POST',
19 headers: {
20 'Content-Type': 'application/json',
21 'Authorization': 'Bearer YOUR_JWT_TOKEN'
22 },
23 body: JSON.stringify({
24 query,
25 variables: { id: userId }
26 })
27 });
28 
29 const { data, errors } = await response.json();
30 
31 if (errors && errors.length > 0) {
32 console.error('GraphQL Execution Errors:', errors);
33 throw new Error(errors[0].message);
34 }
35 
36 console.log('User Data:', data.user);
37 return data.user;
38}

3. Executing Mutations

Mutations modify server state and return the updated fields in the same operation:

1async function updateUserRole(userId, newRole) {
2 const mutation = `
3 mutation UpdateRole($id: ID!, $role: RoleEnum!) {
4 updateUserRole(id: $id, role: $role) {
5 id
6 role
7 updatedAt
8 }
9 }
10 `;
11 
12 const response = await fetch('/graphql', {
13 method: 'POST',
14 headers: { 'Content-Type': 'application/json' },
15 body: JSON.stringify({
16 query: mutation,
17 variables: { id: userId, role: newRole }
18 })
19 });
20 
21 const { data } = await response.json();
22 return data.updateUserRole;
23}

4. Real-Time Subscriptions via WebSockets

Subscriptions use WebSockets (using protocols like graphql-transport-ws) to receive streaming updates when mutations occur on the server:

1// Protocol payload sent over WebSocket connection:
2const subscriptionMessage = {
3 id: 'sub_1',
4 type: 'subscribe',
5 payload: {
6 query: `
7 subscription OnNewMessage($channelId: ID!) {
8 messageAdded(channelId: $channelId) {
9 id
10 sender
11 content
12 timestamp
13 }
14 }
15 `,
16 variables: { channelId: 'general_chat' }
17 }
18};
19 
20socket.send(JSON.stringify(subscriptionMessage));

5. Critical Gotcha: HTTP Status Codes in GraphQL

Unlike REST, GraphQL almost always returns HTTP status 200 OK, even when an error occurs in resolver execution! Always check the response body's errors array:

1// DANGER: response.ok will be true even if user was not found!
2const { data, errors } = await res.json();
3if (errors) {
4 // Handle GraphQL level errors!
5}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What HTTP method is conventionally used to dispatch GraphQL queries and mutations?
Question 2
Why is response.ok === true NOT sufficient to verify success in a GraphQL request?
Question 3
What technology powers real-time GraphQL Subscriptions in the browser?
Question 4
What problem in REST API design is directly resolved by GraphQL field selection?
Question 5
How are dynamic parameters passed safely into a GraphQL query to prevent injection attacks?
Next Lesson

JSON.stringify Replacer & JSON.parse Reviver

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Fetch Interceptors & Request MiddlewareJSON.stringify Replacer & JSON.parse Reviver

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext