Skip to main content

OpenAPI codegen

A pet store client for the public Swagger Petstore API. None of its requests are written by hand: @hyper-fetch/cli reads the OpenAPI spec and generates one file with every endpoint, model and createSdk factory. The app lists pets by status, adds a pet and looks one up by id.

intermediateopenapicreateSdktypescriptuseFetchuseSubmit
import { useFetch, useSubmit } from "@hyper-fetch/react";
import { type FormEvent, useState } from "react";

import type { Components } from "./api/petstore.sdk";
import { client, sdk } from "./client";

// Models from the spec are exported by the generated file too.
type Status = NonNullable<Components.Schemas.Pet["status"]>;
const statuses: Status[] = ["available", "pending", "sold"];

const PetDetails = ({ petId }: { petId: number }) => {
// `:petId` in the spec path types `setParams()`.
const { data, error, loading } = useFetch(sdk.pet.$petId.$get.setParams({ petId }));

if (loading && !data) return <p aria-busy="true">Loading pet {petId}...</p>;
if (error || !data) return <p className="error">Pet {petId} was not found.</p>;
return (
<p>
<strong>{data.name}</strong> <mark>{data.status}</mark> {data.category?.name}
<br />
<small className="muted">GET /pet/{petId}</small>
</p>
);
};

export const App = () => {
const [status, setStatus] = useState<Status>("available");
const [petId, setPetId] = useState<number | null>(null);
const [name, setName] = useState("");

// `status` is a required query param in the spec, so leaving it out does not compile.
const pets = useFetch(sdk.pet.findByStatus.$get.setQueryParams({ status }));
const { submit, submitting, error: createError, onSubmitSuccess } = useSubmit(sdk.pet.$post);

onSubmitSuccess(({ response }) => {
setName("");
setPetId(response.data.id ?? null);
client.cache.invalidate(/findByStatus/);
});

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
// The `Pet` schema types the payload: `name` and `photoUrls` are required.
submit({
payload: {
id: Date.now() % 1_000_000,
name,
photoUrls: [],
status: "available",
},
});
};

return (
<main className="container">
<hgroup>
<h1>Pet store</h1>
<p>Requests generated from the Swagger Petstore OpenAPI spec by @hyper-fetch/cli.</p>
</hgroup>
<div className="grid-2">
<article>
<header>Add a pet</header>
<form onSubmit={handleSubmit}>
<fieldset role="group">
<input value={name} onChange={(event) => setName(event.target.value)} placeholder="Name" required />
<button type="submit" aria-busy={submitting} disabled={submitting}>
Add
</button>
</fieldset>
{createError && <small className="error">Could not add the pet.</small>}
</form>
{petId === null ? (
<p className="muted">Add a pet or pick an id from the list.</p>
) : (
<PetDetails petId={petId} />
)}
</article>
<section>
<div role="group">
{statuses.map((item) => (
<button
key={item}
type="button"
className={item === status ? undefined : "outline"}
onClick={() => setStatus(item)}
>
{item}
</button>
))}
</div>
{pets.loading && !pets.data && <p aria-busy="true">Loading pets...</p>}
{pets.error && <p className="error">Could not load pets.</p>}
<ul className="list">
{pets.data?.slice(0, 12).map((pet) => (
<li key={pet.id}>
<span>{pet.name}</span>
{/* The shared demo data has ids too large for a JavaScript number, those can't be looked up. */}
{pet.id !== undefined && Number.isSafeInteger(pet.id) && (
<button type="button" className="outline secondary" onClick={() => setPetId(pet.id ?? null)}>
#{pet.id}
</button>
)}
</li>
))}
</ul>
</section>
</div>
</main>
);
};
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/openapi-codegen hyper-fetch-react-openapi-codegen && cd hyper-fetch-react-openapi-codegen && npm install && npm run dev
What it shows
  1. hyper-fetch generate turns an OpenAPI spec into a typed SDK file, run from an npm script.
  2. Typed from the spec: required query params, path params, payload fields and response models all come from openapi/petstore.json.
  3. Generated models: Components.Schemas.Pet and the other schemas are exported for your own code.
  4. Regular requests: the generated SDK returns normal HyperFetch requests, used with useFetch and useSubmit.

How it works​

  1. The spec is saved in openapi/petstore.json, so the generated code only changes when you update the spec on purpose. package.json has a script that writes the SDK:

    hyper-fetch generate --template openapi --url openapi/petstore.json --fileName petstore.sdk.ts --overwrite

    --url takes an http(s) URL or a local path. With every flag set, the command never prompts, so it also runs in CI.

  2. api.json is the CLI config. aliases.api is the folder the SDK is written to, here src/api.

  3. src/api/petstore.sdk.ts is the output. It holds the spec models in Components, one RequestModel per operation in SdkSchema, and a createSdk(client) factory. Each path segment is a key and each method a $ key, so GET /pet/{petId} is sdk.pet.$petId.$get.

  4. src/client.ts creates the client with the base URL of the API and calls the generated createSdk. It passes camelCaseToKebabCase: false because OpenAPI paths are literal: /pet/findByStatus must stay camelCase.

  5. App uses the requests like hand-written ones. sdk.pet.findByStatus.$get.setQueryParams({ status }) fails to compile without status, which the spec marks as required. sdk.pet.$petId.$get.setParams({ petId }) takes the {petId} path param. useSubmit(sdk.pet.$post) types the payload from the Pet schema, where name and photoUrls are required.

The Petstore is a shared public demo, so the list changes as other people use it, and some of its ids are larger than a JavaScript number can hold. The app only offers to look up ids it can represent.

When to use it
  • Your backend publishes an OpenAPI or Swagger spec and you want types without writing requests by hand.
  • Third-party APIs with a spec: regenerate when they release a new version and let TypeScript show what changed.
  • Large APIs, where the spec is the single source of truth for dozens of endpoints.

Summary

hyper-fetch generate turns an OpenAPI spec into one file with typed requests and a createSdk factory. Commit the spec and the output, regenerate with an npm script, and use the requests like any other HyperFetch request.