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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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>
);
};
npx tiged BetterTyped/hyper-fetch/examples/react/openapi-codegen hyper-fetch-react-openapi-codegen && cd hyper-fetch-react-openapi-codegen && npm install && npm run devhyper-fetch generateturns an OpenAPI spec into a typed SDK file, run from an npm script.- Typed from the spec: required query params, path params, payload fields and response models all come from
openapi/petstore.json. - Generated models:
Components.Schemas.Petand the other schemas are exported for your own code. - Regular requests: the generated SDK returns normal HyperFetch requests, used with
useFetchanduseSubmit.
How it works
-
The spec is saved in
openapi/petstore.json, so the generated code only changes when you update the spec on purpose.package.jsonhas a script that writes the SDK:hyper-fetch generate --template openapi --url openapi/petstore.json --fileName petstore.sdk.ts --overwrite--urltakes anhttp(s)URL or a local path. With every flag set, the command never prompts, so it also runs in CI. -
api.jsonis the CLI config.aliases.apiis the folder the SDK is written to, heresrc/api. -
src/api/petstore.sdk.tsis the output. It holds the spec models inComponents, oneRequestModelper operation inSdkSchema, and acreateSdk(client)factory. Each path segment is a key and each method a$key, soGET /pet/{petId}issdk.pet.$petId.$get. -
src/client.tscreates the client with the base URL of the API and calls the generatedcreateSdk. It passescamelCaseToKebabCase: falsebecause OpenAPI paths are literal:/pet/findByStatusmust stay camelCase. -
Appuses the requests like hand-written ones.sdk.pet.findByStatus.$get.setQueryParams({ status })fails to compile withoutstatus, 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 thePetschema, wherenameandphotoUrlsare 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.
- 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.
Related
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.
