Connect an HTML Table to a REST API example interface
Connect an HTML Table to a REST API example interface

This example connects an HTML table to a REST API for search, sorting and pagination. The server returns only the requested page; the browser renders it without inserting API text as HTML. It includes a runnable Flask endpoint, a complete frontend and recoverable request states.

Open the working preview · Compare the related templates and components

Build the example

  1. Copy index.html, app.py and requirements.txt into one folder, then run the setup commands below. Open http://127.0.0.1:8760/ so the page and API share an origin.
  2. The request carries page, size, q, sort and direction. The endpoint validates numeric ranges, page sizes and an allowlist of sort fields; a query cannot become an arbitrary column or SQL statement.
  3. The response includes items, page, size, total and pages. Filtering and sorting happen before the slice, so every page refers to the same filtered order. An out-of-range page is clamped to the final page.
  4. Abort the previous request when a new filter starts, and keep a request sequence number so an older response cannot overwrite the latest result. Check response.ok before treating JSON as a successful response.
  5. Keep the real column headers during loading and empty results. The example announces the visible page and offers Retry after a failed request without discarding the search.

Run the local backend

Use Python 3.12 or newer for the tested setup. Save the complete files below together. Flask is pinned at 3.1.3; the production requirements additionally pin Gunicorn 26.2.0. These versions were verified on 3 November 2026.

python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python app.py
# Open http://127.0.0.1:8760/

Production serving

The development server binds to localhost. For a deployed copy, install the production requirements and run the app factory behind your HTTPS reverse proxy. Use a database directory owned by the service account and keep it across deployments.

python -m pip install -r requirements-production.txt
export APP_ENV="production"
export APP_SECRET="a-long-random-secret-kept-on-the-server"
export APP_HOSTS="forms.example.com"
gunicorn --bind 127.0.0.1:8760 --workers 2 "app:create_app()"

Behavior and limits

  • The hosted preview simulates the response shape with fictional local records. Run the included Flask app to exercise real HTTP queries and server-side paging.
  • The sample records are deliberately public and in memory. Real customer data needs authentication, record-level authorization and a database query scoped to the permitted dataset. Filtering in the browser does not establish access control.
  • Use integer cents for the sample money values, then format them for display. The response does not accept prices from the browser or implement billing.

Complete source files

The preview-mode marker in index.html demonstrates the interface without pretending to send data. The included Flask route enables backend mode when it serves that file. Copy the relevant form, styles and script when integrating with a larger template.

Complete index.html

<!doctype html>
<html lang="en" data-backend="preview">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <title>A table connected to a REST API — uiCookies example</title>
    <style>
      * {
        box-sizing: border-box;
      }
      body {
        margin: 0;
        background: #f0f3f5;
        color: #263a47;
        font:
          17px/1.6 system-ui,
          sans-serif;
      }
      main {
        max-width: 1000px;
        margin: 48px auto;
        padding: 32px;
        background: white;
        border: 1px solid #cbd5db;
        border-radius: 6px;
      }
      h1 {
        font-size: clamp(30px, 4vw, 42px);
        line-height: 1.2;
      }
      h2 {
        font-size: 23px;
      }
      button,
      input,
      select,
      textarea {
        font: inherit;
      }
      input,
      select,
      textarea {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #667d8b;
        border-radius: 4px;
        background: white;
        color: #263a47;
      }
      button {
        min-height: 44px;
        padding: 9px 18px;
        border: 1px solid #214e65;
        background: #214e65;
        color: white;
        border-radius: 4px;
        cursor: pointer;
      }
      button:disabled {
        opacity: 0.55;
        cursor: default;
      }
      label {
        display: block;
        font-weight: 600;
        margin: 16px 0 6px;
      }
      fieldset {
        border: 1px solid #b7c8d1;
        border-radius: 4px;
        margin: 20px 0;
        padding: 16px;
      }
      legend {
        font-weight: 700;
        padding: 0 6px;
        font-size: 19px;
      }
      button:focus-visible,
      input:focus-visible,
      select:focus-visible,
      textarea:focus-visible,
      [tabindex]:focus-visible {
        outline: 3px solid #ad4812;
        outline-offset: 3px;
      }
      .notice {
        background: #edf4f8;
        border-left: 4px solid #214e65;
        padding: 14px;
      }
      .error {
        color: #a42626;
        font-weight: 600;
      }
      .field-error {
        margin: 5px 0;
        color: #a42626;
        font-size: 15px;
      }
      [aria-invalid="true"] {
        border: 2px solid #a42626;
      }
      .actions {
        display: flex;
        gap: 12px;
        flex-wrap: wrap;
        align-items: center;
        margin-top: 20px;
      }
      .status {
        min-height: 28px;
      }
      .note {
        font-size: 15px;
        color: #49616e;
      }
      [hidden] {
        display: none !important;
      }
      @media (max-width: 600px) {
        main {
          margin: 16px;
          padding: 22px;
        }
      }
      .toolbar {
        display: flex;
        gap: 16px;
        align-items: end;
        flex-wrap: wrap;
        margin-bottom: 24px;
      }
      .toolbar > div:first-child {
        flex: 1;
        min-width: 180px;
      }
      .toolbar > div:last-child {
        width: 130px;
      }
      .table-wrap {
        overflow: auto;
      }
      table {
        min-width: 580px;
        width: 100%;
        border-collapse: collapse;
      }
      caption {
        text-align: left;
        font-weight: 700;
        margin-bottom: 12px;
      }
      th,
      td {
        padding: 13px 10px;
        border-bottom: 1px solid #cbd5db;
        text-align: left;
      }
      th button {
        padding: 6px 8px;
        min-height: 38px;
        border: 0;
        background: #edf3f6;
        color: #213e4e;
      }
      th[aria-sort="ascending"] button::after {
        content: " ↑";
      }
      th[aria-sort="descending"] button::after {
        content: " ↓";
      }
      .money {
        font-variant-numeric: tabular-nums;
        white-space: nowrap;
      }
    </style>
  </head>
  <body>
    <main>
      <p class="note">UI COOKIES / WORKING EXAMPLE</p>
      <h1>A table connected to a REST API</h1>
      <p class="notice" id="mode">
        Hosted preview: fictional data only. No messages or responses are sent.
      </p>
      <p>
        Search, sorting and paging use a server endpoint when this example runs
        through the included Flask app. The hosted preview simulates the same
        response shape locally.
      </p>
      <div class="toolbar">
        <div>
          <label for="query">Find an invoice or client</label
          ><input
            id="query"
            type="search"
            maxlength="80"
            placeholder="Try Northbank"
          />
        </div>
        <div>
          <label for="size">Rows per page</label
          ><select id="size">
            <option>5</option>
            <option>10</option>
            <option>20</option>
          </select>
        </div>
      </div>
      <div
        class="table-wrap"
        role="region"
        tabindex="0"
        aria-label="Invoice records"
        aria-busy="false"
      >
        <table>
          <caption>
            Fictional invoices — values in USD
          </caption>
          <thead>
            <tr>
              <th scope="col" data-key="id">
                <button type="button">ID</button>
              </th>
              <th scope="col" data-key="client">
                <button type="button">Client</button>
              </th>
              <th scope="col" data-key="amount">
                <button type="button">Amount</button>
              </th>
              <th scope="col" data-key="status">
                <button type="button">Status</button>
              </th>
            </tr>
          </thead>
          <tbody id="rows"></tbody>
        </table>
      </div>
      <p id="summary" class="status" role="status"></p>
      <p id="error" class="error" role="alert" hidden></p>
      <div class="actions">
        <button id="previous" type="button">Previous page</button
        ><button id="next" type="button">Next page</button
        ><button id="retry" type="button" hidden>Retry request</button>
      </div>
    </main>
    <script>
      const FIXTURE = [
          {
            id: 1,
            client: "Fieldwork Sample",
            amount: 7625,
            status: "Pending",
          },
          { id: 2, client: "Harbour Demo", amount: 7750, status: "Overdue" },
          { id: 3, client: "Studio Example", amount: 7875, status: "Paid" },
          { id: 4, client: "Northbank Demo", amount: 8000, status: "Pending" },
          {
            id: 5,
            client: "Fieldwork Sample",
            amount: 8125,
            status: "Overdue",
          },
          { id: 6, client: "Harbour Demo", amount: 8250, status: "Paid" },
          { id: 7, client: "Studio Example", amount: 8375, status: "Pending" },
          { id: 8, client: "Northbank Demo", amount: 8500, status: "Overdue" },
          { id: 9, client: "Fieldwork Sample", amount: 8625, status: "Paid" },
          { id: 10, client: "Harbour Demo", amount: 8750, status: "Pending" },
          { id: 11, client: "Studio Example", amount: 8875, status: "Overdue" },
          { id: 12, client: "Northbank Demo", amount: 9000, status: "Paid" },
          {
            id: 13,
            client: "Fieldwork Sample",
            amount: 9125,
            status: "Pending",
          },
          { id: 14, client: "Harbour Demo", amount: 9250, status: "Overdue" },
          { id: 15, client: "Studio Example", amount: 9375, status: "Paid" },
          { id: 16, client: "Northbank Demo", amount: 9500, status: "Pending" },
          {
            id: 17,
            client: "Fieldwork Sample",
            amount: 9625,
            status: "Overdue",
          },
          { id: 18, client: "Harbour Demo", amount: 9750, status: "Paid" },
          { id: 19, client: "Studio Example", amount: 9875, status: "Pending" },
          {
            id: 20,
            client: "Northbank Demo",
            amount: 10000,
            status: "Overdue",
          },
          { id: 21, client: "Fieldwork Sample", amount: 10125, status: "Paid" },
          { id: 22, client: "Harbour Demo", amount: 10250, status: "Pending" },
          {
            id: 23,
            client: "Studio Example",
            amount: 10375,
            status: "Overdue",
          },
          { id: 24, client: "Northbank Demo", amount: 10500, status: "Paid" },
          {
            id: 25,
            client: "Fieldwork Sample",
            amount: 10625,
            status: "Pending",
          },
          { id: 26, client: "Harbour Demo", amount: 10750, status: "Overdue" },
          { id: 27, client: "Studio Example", amount: 10875, status: "Paid" },
          {
            id: 28,
            client: "Northbank Demo",
            amount: 11000,
            status: "Pending",
          },
          {
            id: 29,
            client: "Fieldwork Sample",
            amount: 11125,
            status: "Overdue",
          },
          { id: 30, client: "Harbour Demo", amount: 11250, status: "Paid" },
          {
            id: 31,
            client: "Studio Example",
            amount: 11375,
            status: "Pending",
          },
          {
            id: 32,
            client: "Northbank Demo",
            amount: 11500,
            status: "Overdue",
          },
          { id: 33, client: "Fieldwork Sample", amount: 11625, status: "Paid" },
          { id: 34, client: "Harbour Demo", amount: 11750, status: "Pending" },
          {
            id: 35,
            client: "Studio Example",
            amount: 11875,
            status: "Overdue",
          },
          { id: 36, client: "Northbank Demo", amount: 12000, status: "Paid" },
          {
            id: 37,
            client: "Fieldwork Sample",
            amount: 12125,
            status: "Pending",
          },
          { id: 38, client: "Harbour Demo", amount: 12250, status: "Overdue" },
          { id: 39, client: "Studio Example", amount: 12375, status: "Paid" },
          {
            id: 40,
            client: "Northbank Demo",
            amount: 12500,
            status: "Pending",
          },
          {
            id: 41,
            client: "Fieldwork Sample",
            amount: 12625,
            status: "Overdue",
          },
          { id: 42, client: "Harbour Demo", amount: 12750, status: "Paid" },
          {
            id: 43,
            client: "Studio Example",
            amount: 12875,
            status: "Pending",
          },
          {
            id: 44,
            client: "Northbank Demo",
            amount: 13000,
            status: "Overdue",
          },
          { id: 45, client: "Fieldwork Sample", amount: 13125, status: "Paid" },
          { id: 46, client: "Harbour Demo", amount: 13250, status: "Pending" },
          {
            id: 47,
            client: "Studio Example",
            amount: 13375,
            status: "Overdue",
          },
        ],
        ready = document.documentElement.dataset.backend === "ready",
        tbody = document.querySelector("#rows"),
        query = document.querySelector("#query"),
        size = document.querySelector("#size"),
        summary = document.querySelector("#summary"),
        error = document.querySelector("#error"),
        region = document.querySelector(".table-wrap"),
        prev = document.querySelector("#previous"),
        next = document.querySelector("#next"),
        retry = document.querySelector("#retry");
      if (ready)
        document.querySelector("#mode").textContent =
          "Connected to the local sample API. These records are fictional and public.";
      let page = 1,
        pages = 1,
        sort = "id",
        direction = "asc",
        requestNumber = 0,
        controller,
        debounce;
      function fixture() {
        let items = FIXTURE.filter((r) =>
          (r.id + " " + r.client + " " + r.status)
            .toLowerCase()
            .includes(query.value.trim().toLowerCase()),
        );
        items.sort(
          (a, b) =>
            ((a[sort] > b[sort]) - (a[sort] < b[sort])) *
            (direction === "asc" ? 1 : -1),
        );
        const total = items.length,
          n = Number(size.value),
          count = Math.max(1, Math.ceil(total / n)),
          current = Math.min(page, count);
        return {
          items: items.slice((current - 1) * n, current * n),
          page: current,
          pages: count,
          total,
          size: n,
        };
      }
      function render(data) {
        tbody.replaceChildren();
        for (const row of data.items) {
          const tr = document.createElement("tr");
          for (const key of ["id", "client", "amount", "status"]) {
            const cell = document.createElement(key === "id" ? "th" : "td");
            if (key === "id") cell.scope = "row";
            cell.textContent =
              key === "amount"
                ? new Intl.NumberFormat("en-US", {
                    style: "currency",
                    currency: "USD",
                  }).format(row.amount / 100)
                : String(row[key]);
            if (key === "amount") cell.className = "money";
            tr.append(cell);
          }
          tbody.append(tr);
        }
        if (!data.items.length) {
          const tr = document.createElement("tr"),
            td = document.createElement("td");
          td.colSpan = 4;
          td.textContent =
            "No invoices match these filters. Clear the search to try again.";
          tr.append(td);
          tbody.append(tr);
        }
        page = data.page;
        pages = data.pages;
        summary.textContent =
          data.total + " records · page " + page + " of " + pages;
        document.querySelectorAll("th[data-key]").forEach((th) => {
          th.removeAttribute("aria-sort");
          if (th.dataset.key === sort)
            th.setAttribute(
              "aria-sort",
              direction === "asc" ? "ascending" : "descending",
            );
        });
      }
      async function load() {
        const serial = ++requestNumber;
        controller?.abort();
        controller = new AbortController();
        region.setAttribute("aria-busy", "true");
        prev.disabled = next.disabled = true;
        error.hidden = retry.hidden = true;
        summary.textContent = "Loading invoices…";
        try {
          let data;
          if (ready) {
            const params = new URLSearchParams({
              page: String(page),
              size: size.value,
              q: query.value,
              sort,
              direction,
            });
            const r = await fetch("/api/invoices?" + params, {
              signal: controller.signal,
            });
            data = await r.json();
            if (!r.ok) throw Error(data.message || "The request failed.");
          } else data = fixture();
          if (serial !== requestNumber) return;
          render(data);
        } catch (e) {
          if (e.name === "AbortError") return;
          if (serial !== requestNumber) return;
          summary.textContent = "";
          error.textContent = e.message || "Could not load invoices.";
          error.hidden = false;
          retry.hidden = false;
        } finally {
          if (serial === requestNumber) {
            region.setAttribute("aria-busy", "false");
            prev.disabled = page <= 1;
            next.disabled = page >= pages;
          }
        }
      }
      query.addEventListener("input", () => {
        clearTimeout(debounce);
        page = 1;
        debounce = setTimeout(load, 200);
      });
      size.addEventListener("change", () => {
        page = 1;
        load();
      });
      prev.addEventListener("click", () => {
        page--;
        load();
      });
      next.addEventListener("click", () => {
        page++;
        load();
      });
      retry.addEventListener("click", load);
      document.querySelectorAll("th button").forEach((b) =>
        b.addEventListener("click", () => {
          const key = b.parentElement.dataset.key;
          direction = key === sort && direction === "asc" ? "desc" : "asc";
          sort = key;
          page = 1;
          load();
        }),
      );
      load();
    </script>
  </body>
</html>
Complete app.py

"""Public fictional invoices for an HTML table tutorial; no private records or auth service."""
from pathlib import Path
from flask import Flask, jsonify, request

ROWS = [{"id": i, "client": ["Northbank Demo", "Fieldwork Sample", "Harbour Demo", "Studio Example"][i % 4], "amount": 7500 + i * 125, "status": ["Paid", "Pending", "Overdue"][i % 3]} for i in range(1, 48)]

def create_app(config=None):
    app = Flask(__name__, static_folder=None)
    if config:
        app.config.update(config)

    @app.get("/")
    def index():
        return Path(__file__).with_name("index.html").read_text().replace('data-backend="preview"', 'data-backend="ready"')

    @app.get("/api/invoices")
    def invoices():
        # This sample dataset is intentionally public. Add real authorization and
        # dataset scoping before replacing it with private customer records.
        try:
            page = int(request.args.get("page", "1"))
            size = int(request.args.get("size", "5"))
        except ValueError:
            return jsonify(message="Page and page size must be integers."), 400
        sort = request.args.get("sort", "id")
        direction = request.args.get("direction", "asc")
        query = request.args.get("q", "").strip()
        if not 1 <= page <= 10000 or size not in (5, 10, 20) or sort not in ("id", "client", "amount", "status") or direction not in ("asc", "desc") or len(query) > 80:
            return jsonify(message="Invalid table query."), 400
        rows = [row for row in ROWS if query.casefold() in (str(row["id"]) + " " + row["client"] + " " + row["status"]).casefold()]
        rows.sort(key=lambda row: row[sort], reverse=direction == "desc")
        total = len(rows)
        pages = max(1, (total + size - 1) // size)
        page = min(page, pages)
        start = (page - 1) * size
        response = jsonify(items=rows[start:start + size], page=page, size=size, total=total, pages=pages)
        response.headers["Cache-Control"] = "no-store"
        return response

    return app

if __name__ == "__main__":
    create_app().run(host="127.0.0.1", port=8760, debug=False)
Complete requirements.txt

Flask==3.1.3
Complete requirements-production.txt

-r requirements.txt
gunicorn==26.2.0

What was tested

  • Default page, a filtered result, descending numeric sort and an empty result.
  • Invalid page, size, sort, direction and overly long search values.
  • Browser next-page navigation, changing a search, an injected request failure and a successful retry.

The example interface was checked at 320, 390 and 1440 pixels with keyboard and automated accessibility checks. Backend examples also have isolated server tests; the form and RSVP tests use a test mail transport.

Documentation

Aigars Silkalns

Designed & written by Aigars Silkalns

Aigars Silkalns is a Latvian entrepreneur and web developer who founded Colorlib, a hub for distinctive WordPress themes. Trained in technology and design, he began as a freelancer and launched Colorlib in 2013, earning acclaim for user-friendly, modern, responsive themes. A champion of open source, Silkalns shares insights on web trends and entrepreneurship. His mission is to make web design simple and accessible, empowering people worldwide to build professional sites with ease.

XLinkedInMore about uiCookies →

uiCookies content is free. When you buy through links on our site, we may earn an affiliate commission.