EthicsComputerCourses
Join training +91 90532 10052

HTML Integration with GraphQL

HTML · Lesson 197 of 234 Advanced 12 min read Updated

By the end of this lesson you will be able to explain how GraphQL differs from REST, send a query with variables using fetch, turn the response into safe HTML, read the errors array correctly and give each UI component its own fragment.

What you should know first: Fetch API Integration, HTML with REST APIs, HTML with Modern JavaScript and Template Element. HTML Integration with RESTful APIs covers caching and authentication, which work the same way here.

GraphQL and REST in plain words

Think of two college canteens. The REST canteen has one counter per dish: a counter for the thali, another for the sweets, another for the drinks. Each counter gives a fixed plate. The GraphQL canteen has one counter and an order slip. You write down exactly what you want, and you get exactly that on one tray.

GraphQL is a query language for APIs. The server publishes a schema: a typed list of everything you can ask for. The client sends a query that names the fields it wants, and the server answers with JSON in the same shape.

RESTGraphQL
AddressesMany URLs, such as /trains/12124Usually one, such as /graphql
Who picks the fieldsThe serverThe client, field by field
Related dataOften several requestsOne query can follow links
ErrorsMostly the HTTP status codeAn errors array in the JSON body
HTTP cachingEasy: each URL is a resourceHarder: most queries are POST to one URL

GraphQL shines when many screens need different slices of the same data, such as an app and a website sharing one API. For a small site, REST is often simpler.

A query and its response

Here is part of a schema for a railway enquiry service. String! means "a string that is never null". [Train!]! means "a list of trains".

Text
type Train {
  number: String!
  name: String!
  to: String!
  seatsLeft: Int!
  fare: Int
}

type Query {
  train(number: String!): Train
  trains(from: String!): [Train!]!
}

A query asks for one train and only three of its fields. $n is a variable: a placeholder whose value travels separately, like a blank on a form.

Text
query TrainCard($n: String!) {
  train(number: $n) { name to seatsLeft }
}

The response mirrors the query exactly, wrapped in a data key:

JSON
{"data":{"train":{"name":"Deccan Queen","to":"Mumbai CSMT","seatsLeft":18}}}

fare and number are missing because the query did not ask for them: no extra data, no missing data.

Sending a query with fetch

You do not need a library to talk to GraphQL. It is an ordinary POST request whose body is JSON with a query string and an optional variables object.

JavaScript
async function runQuery(query, variables = {}) {
  const res = await fetch("/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query, variables }),
  });
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json(); // { data, errors }
}

Never paste user input into the query string, such as train(number: "${input}"). Put values in variables, so the server checks their types.

The errors array and the HTTP status

This is where beginners trip. A GraphQL server often answers 200 OK even when something went wrong. The problem is reported inside the JSON. Here is real output from the small Node server shown later in this lesson. All three requests used query TrainCard($n: String!) { train(number: $n) { ... } } with $n set to "12124". Inside the braces they asked for name to seatsLeft, then name platform, then name fare:

Output
200 {"data":{"train":{"name":"Deccan Queen","to":"Mumbai CSMT","seatsLeft":18}}}
200 {"errors":[{"message":"Cannot query field \"platform\" on type \"Train\".","locations":[{"line":1,"column":57}]}]}
200 {"errors":[{"message":"Fare service is down","locations":[{"line":1,"column":57}],"path":["train","fare"]}],"data":{"train":{"name":"Deccan Queen","fare":null}}}
  • The first query worked.
  • The second asked for a field that does not exist. It failed validation, so nothing ran and there is no data.
  • The third is a partial success: fare is null but the name arrived, and path shows which field broke.

So check errors as well as res.ok, and decide per screen whether partial data is useful. A train card without a fare is fine; a payment summary without a total is not.

Step 1: query, render and handle errors

The Try-it editor cannot reach a GraphQL server, so this page carries a clearly marked mock server: a toy function that understands simple queries and returns a real Response. Swap mockFetch for fetch to use a real server. Each card is a <template> clone filled with textContent. Try all three buttons.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>GraphQL train search</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    .card { border: 1px solid #ccc; border-radius: 8px; padding: 8px 12px; margin: 6px 0; list-style: none; }
    .err { color: #b71c1c; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; font-size: 13px; }
  </style>
</head>
<body>
  <h1>Trains from Pune</h1>
  <button id="ok">Good query</button>
  <button id="typo">Unknown field</button>
  <button id="fare">Ask for fare</button>
  <ul id="errors" class="err"></ul>
  <ul id="list"></ul>
  <pre id="raw"></pre>

  <template id="card">
    <li class="card"><strong class="name"></strong> to <span class="to"></span>:
      <span class="seats"></span> <span class="fare"></span><br><small class="remark"></small></li>
  </template>

  <script>
    // ---- MOCK SERVER: a toy for this page, not a real GraphQL engine ----
    const TRAINS = [
      { __typename: "Train", number: "12124", name: "Deccan Queen", from: "Pune", to: "Mumbai CSMT",
        seatsLeft: 18, remark: "Pantry <b>closed</b> today", fare: () => { throw new Error("Fare service is down"); } },
      { __typename: "Train", number: "12939", name: "Pune Jaipur Express", from: "Pune", to: "Jaipur",
        seatsLeft: 0, remark: "", fare: () => { throw new Error("Fare service is down"); } }
    ];
    function parse(doc) {
      const t = doc.replace(/\([^)]*\)/g, "").match(/\.\.\.|[{}]|\w+/g);
      let i = 0;
      const block = () => {
        const sel = []; i++;
        while (t[i] !== "}") {
          if (t[i] === "...") { sel.push({ spread: t[i + 1] }); i += 2; }
          else { const f = { name: t[i++] }; if (t[i] === "{") f.sel = block(); sel.push(f); }
        }
        i++; return sel;
      };
      const fragments = {}; let op;
      while (i < t.length) {
        if (t[i] === "fragment") { const name = t[i + 1]; i += 4; fragments[name] = block(); }
        else { while (t[i] !== "{") i++; op = block(); }
      }
      return { op, fragments };
    }
    async function mockFetch(url, options) {
      const { query, variables = {} } = JSON.parse(options.body);
      const { op, fragments } = parse(query);
      const invalid = new Set(), errors = [];
      const expand = (sel) => sel.flatMap((f) => f.spread ? expand(fragments[f.spread]) : [f]);
      const pick = (obj, sel, path) => {
        if (obj === null) return null;
        if (Array.isArray(obj)) return obj.map((o, n) => pick(o, sel, [...path, n]));
        const out = {};
        for (const f of expand(sel)) {
          if (!(f.name in obj)) { invalid.add(`Cannot query field "${f.name}" on type "${obj.__typename}".`); continue; }
          try {
            const v = typeof obj[f.name] === "function" ? obj[f.name]() : obj[f.name];
            out[f.name] = f.sel ? pick(v, f.sel, [...path, f.name]) : v;
          } catch (e) { out[f.name] = null; errors.push({ message: e.message, path: [...path, f.name] }); }
        }
        return out;
      };
      const root = { __typename: "Query", trains: () => TRAINS.filter((x) => x.from === variables.from) };
      const data = pick(root, op, []);
      const body = invalid.size ? { errors: [...invalid].map((message) => ({ message })) }
                 : errors.length ? { errors, data } : { data };
      return new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json" } });
    }
    // ---- END OF MOCK SERVER ----

    async function runQuery(query, variables = {}) {
      const res = await mockFetch("/graphql", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query, variables })
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      const json = await res.json();
      document.querySelector("#raw").textContent = res.status + " " + JSON.stringify(json, null, 1);
      return json;
    }

    function render({ data, errors }) {
      const list = document.querySelector("#list");
      const errorList = document.querySelector("#errors");
      list.replaceChildren();
      errorList.replaceChildren();
      for (const e of errors ?? []) {
        const li = document.createElement("li");
        li.textContent = e.message + (e.path ? ` (at ${e.path.join(".")})` : "");
        errorList.append(li);
      }
      for (const train of data?.trains ?? []) {
        const card = document.querySelector("#card").content.cloneNode(true);
        card.querySelector(".name").textContent = train.name;
        card.querySelector(".to").textContent = train.to;
        card.querySelector(".seats").textContent = train.seatsLeft > 0 ? `${train.seatsLeft} seats` : "Waitlist";
        if ("fare" in train) card.querySelector(".fare").textContent = train.fare ?? "(fare unavailable)";
        card.querySelector(".remark").textContent = train.remark;
        list.append(card);
      }
    }

    const ask = (fields) => runQuery(`query Trains($from: String!) { trains(from: $from) { ${fields} } }`, { from: "Pune" }).then(render);
    document.querySelector("#ok").addEventListener("click", () => ask("name to seatsLeft remark"));
    document.querySelector("#typo").addEventListener("click", () => ask("name platform"));
    document.querySelector("#fare").addEventListener("click", () => ask("name to seatsLeft fare remark"));
  </script>
</body>
</html>

"Good query" shows two cards, and the Deccan Queen remark reads Pantry <b>closed</b> today with the tags visible, because textContent never parses HTML. "Unknown field" shows only an error and no cards. "Ask for fare" shows both cards with "(fare unavailable)" and two errors whose paths end in fare. The status is 200 every time.

Rendering results safely

GraphQL data is still data that people typed, so the rules from Cross-Site Scripting (XSS) Prevention apply unchanged. Fill elements with textContent or <template> clones, never with innerHTML strings. Sanitise a field that really holds rich HTML first. Treat null as a normal value, because any nullable field may come back null.

Fragments: one per UI component

A fragment is a named, reusable list of fields for one type. The professional pattern is to give every UI component its own fragment, kept in the same file as the component. The card says what the card needs; the page query just spreads it with ....

It works like a tiffin service. Each family hands over its own order slip, and the dabbawala bundles them into one delivery. If Ananya's family wants curd tomorrow, only her slip changes.

Step 2: compose a page query from component fragments

Each component below has a fragment string and a render function. The page query adds the fragment text after the operation, as GraphQL clients do.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Fragments per component</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; }
    article { border: 1px solid #ccc; border-radius: 8px; padding: 8px 12px; margin: 6px 0; }
    .badge { padding: 2px 8px; border-radius: 10px; background: #e8f5e9; }
    .badge.full { background: #ffebee; }
    pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; font-size: 13px; }
  </style>
</head>
<body>
  <h1>Pune departures</h1>
  <div id="app"></div>
  <h2>Query sent</h2>
  <pre id="query"></pre>

  <script>
    // ---- MOCK SERVER: a toy for this page, not a real GraphQL engine ----
    const TRAINS = [
      { __typename: "Train", number: "12124", name: "Deccan Queen", from: "Pune", to: "Mumbai CSMT", seatsLeft: 18 },
      { __typename: "Train", number: "12939", name: "Pune Jaipur Express", from: "Pune", to: "Jaipur", seatsLeft: 0 }
    ];
    function parse(doc) {
      const t = doc.replace(/\([^)]*\)/g, "").match(/\.\.\.|[{}]|\w+/g);
      let i = 0;
      const block = () => {
        const sel = []; i++;
        while (t[i] !== "}") {
          if (t[i] === "...") { sel.push({ spread: t[i + 1] }); i += 2; }
          else { const f = { name: t[i++] }; if (t[i] === "{") f.sel = block(); sel.push(f); }
        }
        i++; return sel;
      };
      const fragments = {}; let op;
      while (i < t.length) {
        if (t[i] === "fragment") { const name = t[i + 1]; i += 4; fragments[name] = block(); }
        else { while (t[i] !== "{") i++; op = block(); }
      }
      return { op, fragments };
    }
    async function mockFetch(url, options) {
      const { query, variables = {} } = JSON.parse(options.body);
      const { op, fragments } = parse(query);
      const expand = (sel) => sel.flatMap((f) => f.spread ? expand(fragments[f.spread]) : [f]);
      const pick = (obj, sel) => {
        if (Array.isArray(obj)) return obj.map((o) => pick(o, sel));
        const out = {};
        for (const f of expand(sel)) {
          const v = typeof obj[f.name] === "function" ? obj[f.name]() : obj[f.name];
          out[f.name] = f.sel ? pick(v, f.sel) : v;
        }
        return out;
      };
      const root = { trains: () => TRAINS.filter((x) => x.from === variables.from) };
      return new Response(JSON.stringify({ data: pick(root, op) }), { headers: { "Content-Type": "application/json" } });
    }
    // ---- END OF MOCK SERVER ----

    const SeatBadge = {
      fragment: `fragment SeatBadge on Train { seatsLeft }`,
      render(train) {
        const span = document.createElement("span");
        span.className = train.seatsLeft > 0 ? "badge" : "badge full";
        span.textContent = train.seatsLeft > 0 ? `${train.seatsLeft} seats` : "Waitlist";
        return span;
      }
    };

    const TrainCard = {
      fragment: `fragment TrainCard on Train { number name to ...SeatBadge }`,
      render(train) {
        const article = document.createElement("article");
        const h2 = document.createElement("h2");
        h2.textContent = `${train.number} ${train.name}`;
        const p = document.createElement("p");
        p.append(`To ${train.to} `, SeatBadge.render(train));
        article.append(h2, p);
        return article;
      }
    };

    const PAGE_QUERY = `query Departures($from: String!) {
  trains(from: $from) { ...TrainCard }
}
${TrainCard.fragment}
${SeatBadge.fragment}`;

    (async () => {
      document.querySelector("#query").textContent = PAGE_QUERY;
      const res = await mockFetch("/graphql", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ query: PAGE_QUERY, variables: { from: "Pune" } })
      });
      const { data } = await res.json();
      document.querySelector("#app").append(...data.trains.map((t) => TrainCard.render(t)));
    })();
  </script>
</body>
</html>

You should see two cards, "12124 Deccan Queen" with a green "18 seats" badge and "12939 Pune Jaipur Express" with a red "Waitlist" badge, and the full query below them. Now add from to the TrainCard fragment and print it in render. The page query picks it up with no other change.

A real GraphQL server in Node

The graphql package is the reference implementation of GraphQL in JavaScript (version 17.1.0 checked on npm in November 2026). This small server produced the outputs earlier in the lesson. It is plain code: run it with Node, not in the browser.

JavaScript
import http from "node:http";
import { buildSchema, graphql } from "graphql";

const schema = buildSchema(`
  type Train { number: String! name: String! to: String! seatsLeft: Int! fare: Int }
  type Query { train(number: String!): Train }
`);

const trains = [
  { number: "12124", name: "Deccan Queen", to: "Mumbai CSMT", seatsLeft: 18,
    fare: () => { throw new Error("Fare service is down"); } },
];
const rootValue = {
  train: ({ number }) => trains.find((t) => t.number === number) ?? null,
};

http.createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/graphql") return res.writeHead(404).end();
  let body = "";
  for await (const chunk of req) body += chunk;
  const { query, variables } = JSON.parse(body);
  const result = await graphql({ schema, source: query, rootValue, variableValues: variables });
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify(result));
}).listen(4000);

A resolver is the function that produces one field's value; here fare throws to imitate a broken service. An unknown train number is not an error: the answer is {"data":{"train":null}}, because train is nullable. Real projects use a ready server package such as graphql-http, GraphQL Yoga or Apollo Server, which handle GET requests, content types and status codes.

Client libraries: Apollo and urql

Plain fetch is enough for a few queries. Larger apps use a client library that adds a cache (so a second screen asking for the same train needs no request), loading states and framework hooks. Versions checked on npm in November 2026: Apollo Client 4.3.8 and urql 5.0.4, whose core package is @urql/core 6.0.3.

JavaScript
import { ApolloClient, HttpLink, InMemoryCache, gql } from "@apollo/client";

const client = new ApolloClient({
  link: new HttpLink({ uri: "http://localhost:4000/graphql" }),
  cache: new InMemoryCache(),
});

const TRAIN = gql`
  query TrainCard($n: String!) {
    train(number: $n) { number name seatsLeft }
  }
`;

const { data } = await client.query({ query: TRAIN, variables: { n: "12124" } });
console.log(data.train);
Output
{
  __typename: 'Train',
  number: '12124',
  name: 'Deccan Queen',
  seatsLeft: 18
}

Apollo added __typename to the query by itself. Its cache combines the type name with the id (or _id) field to store each object once, so every screen showing that train updates together. Our type has number instead, so a real app would tell the cache to use it as the key.

The same query with urql looks like this. Note one difference: urql sends queries as GET requests by default when the URL stays short, and our server accepts only POST.

JavaScript
import { Client, cacheExchange, fetchExchange, gql } from "@urql/core";

const client = new Client({
  url: "http://localhost:4000/graphql",
  exchanges: [cacheExchange, fetchExchange],
  preferGetMethod: false, // our small server accepts POST only
});

const TRAIN = gql`
  query TrainCard($n: String!) {
    train(number: $n) { number name seatsLeft }
  }
`;

const result = await client.query(TRAIN, { n: "12124" }).toPromise();
console.log(result.error, result.data.train);
Output
undefined {
  number: '12124',
  name: 'Deccan Queen',
  seatsLeft: 18,
  __typename: 'Train'
}

In React, both libraries give you hooks (useQuery) instead of these calls; see HTML Integration with React.

Common mistakes

  • Trusting res.ok alone. A 200 response can carry an errors array and no data.
  • Gluing user input into the query string. Use variables.
  • Asking for every field "just in case". It brings back the over-fetching GraphQL was meant to remove.
  • One giant page query nobody owns. Give each component its own fragment.
  • Rendering with innerHTML. GraphQL results are user data; use textContent or templates.
  • Crashing on null. Nullable fields can be null when a resolver fails.

Interview questions

1. What is the main difference between GraphQL and REST?

REST exposes many URLs, each returning a fixed shape decided by the server. GraphQL usually exposes one endpoint with a typed schema, and the client's query decides exactly which fields come back. This avoids both over-fetching and making several requests for related data.

2. How do you send a GraphQL query without a library?

Send a POST request with fetch to the GraphQL endpoint, with Content-Type: application/json and a body of JSON.stringify({ query, variables }). Then parse the JSON and read both data and errors.

3. Why can a GraphQL request fail even with HTTP status 200?

Many servers report problems inside the response body. Validation errors return an errors array with no data, and a failing resolver returns partial data with null in that field plus an error with a path. Client code must check errors, not just the status.

4. What are fragments, and why put one next to each component?

A fragment is a named set of fields on a type that can be spread into queries with ...Name. Keeping a fragment beside each component means the component declares its own data needs, and the page query is built from those fragments, so changing a component does not mean hunting through page queries.

5. Why use variables instead of building the query string?

Variables keep values separate from the query text, so the server checks their types and a malicious value cannot change the query. The query text also stays the same between calls, which helps caching.

Key points

  • GraphQL uses one endpoint and a typed schema; the client chooses the fields and the response mirrors the query.
  • A query is a POST with JSON { query, variables }; plain fetch is enough.
  • Check the errors array: validation errors give no data, resolver errors give partial data with null and a path.
  • Render results with textContent or <template> clones, never innerHTML strings.
  • Give each UI component a fragment and build page queries from them.
  • Apollo Client and urql add caching and hooks; both add __typename to queries for their caches.

Exercise

Build a page for Kabir's bookshop in Jaipur. Using the Step 1 mock pattern, give the mock a list of three books with title, author, price and stock, and a root field books that returns them. Write a BookRow component with its own fragment and a render function that returns a table row. Build the page query from the fragment, send it with variables-ready code, show the rows in a <table> with a caption, and show any errors messages above the table. Finally, ask for a field that does not exist and check that your page shows the error instead of crashing.

Show solution
JavaScript
const BookRow = {
  fragment: `fragment BookRow on Book { title author price stock }`,
  render(book) {
    const tr = document.createElement("tr");
    for (const value of [book.title, book.author, `₹${book.price}`, book.stock > 0 ? "In stock" : "Sold out"]) {
      const td = document.createElement("td");
      td.textContent = value;
      tr.append(td);
    }
    return tr;
  }
};

const QUERY = `query Shelf { books { ...BookRow } }
${BookRow.fragment}`;

const res = await mockFetch("/graphql", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ query: QUERY, variables: {} })
});
const { data, errors } = await res.json();
document.querySelector("#errors").textContent = (errors ?? []).map((e) => e.message).join(" ");
document.querySelector("tbody").replaceChildren(...(data?.books ?? []).map((b) => BookRow.render(b)));

Each book in the mock needs __typename: "Book", and the root object gets books: () => BOOKS. Changing the fragment to ask for isbn makes the mock return only an errors array, so the table empties and the message appears above it. Wrap the code in an async function, or use a module script, so await works.

Quick Quiz

1. What does a GraphQL response contain when the query asks for a field that is not in the schema?

2. Where should a user-typed train number go in a GraphQL request?

3. A response has data.train.fare set to null and an error with path: ["train", "fare"]. What happened?

4. Why do GraphQL clients such as Apollo add __typename to queries?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call