Generate SWR hooks from OpenAPI schemas
npm install swr-openapi
Generate swr hooks using OpenAPI schemas
swr-openapi is a type-safe wrapper around swr.
It works by using openapi-fetch and openapi-typescript so you get all the following features:
- ✅ No typos in URLs or params.
- ✅ All parameters, request bodies, and responses are type-checked and 100% match your schema
- ✅ No manual typing of your API
- ✅ Eliminates any types that hide bugs
- ✅ Also eliminates as type overrides that can also hide bugs
``tsx [src/my-component.ts]
import createClient from "openapi-fetch";
import { createQueryHook } from "swr-openapi";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript
const client = createClient
baseUrl: "https://myapi.dev/v1/",
});
const useQuery = createQueryHook(client, "my-api");
function MyComponent() {
const { data, error, isLoading, isValidating, mutate } = useQuery(
"/blogposts/{post_id}",
{
params: {
path: { post_id: "123" },
},
},
);
if (isLoading || !data) return "Loading...";
if (error) return An error occured: ${error.message};
return