Skip to main content
DOCS

SDK examples

CRUD, pagination, typed operations, batching, React, Next.js, and error handling — copy-paste ready.

Fetching a list

import { ws } from "@/lib/codata";

const books = await ws.get("/books");
// fully typed from your spec — no manual interfaces needed

Creating a record

const newBook = await ws.post("/books", {
  title: "The Pragmatic Programmer",
  author: "Hunt & Thomas",
  year: 1999,
});

Filtering & pagination

const recent = await ws.get("/books", { year_gte: "2020", limit: "20", offset: "0" });

// or let the SDK paginate for you
import { paginate, paginateAll } from "codata-io";

for await (const book of paginate(ws, "/books")) {
  console.log(book.title);
}
const everything = await paginateAll(ws, "/books");

Typed operations from your OpenAPI spec

const ops = await ws.operations();

const all = await ops.listBooks();
const one = await ops.getBookById({ id: "123" });
const made = await ops.createBook({ title: "Dune" });

Batch writes with concurrency control

import { batch } from "codata-io";

await batch(ws, [
  { method: "POST", path: "/books", body: { title: "A" } },
  { method: "POST", path: "/books", body: { title: "B" } },
], { concurrency: 3 });

In a React component

import { useEffect, useState } from "react";
import { ws } from "@/lib/codata";

export function BookList() {
  const [books, setBooks] = useState<Awaited<ReturnType<typeof ws.get>>>([]);

  useEffect(() => {
    ws.get("/books").then(setBooks);
  }, []);

  return (
    <ul>
      {books.map((b) => <li key={b.id}>{b.title}</li>)}
    </ul>
  );
}

Server-side (Next.js route handler)

// app/api/books/route.ts
import { ws } from "@/lib/codata";
import { NextResponse } from "next/server";

export async function GET() {
  const books = await ws.get("/books");
  return NextResponse.json(books);
}

Error handling

import { ApiError, AuthError, NotFoundError, TimeoutError, ValidationError } from "codata-io";

try {
  await ws.get("/books/nope");
} catch (err) {
  if (err instanceof NotFoundError) return null;
  if (err instanceof AuthError) redirectToLogin();
  throw err;
}

Golden rule: use the SDK response shapes directly. Don't add mappers, adapters, or duplicate interfaces — the Codata types are the single source of truth.