<p align="center">
  <h1 align="center">swr-openapi</h1>
</p>

<p align="center">Generate <a href="https://swr.vercel.app"><code>swr</code></a> hooks using <a href="https://swagger.io/specification/">OpenAPI</a> schemas</p>

<p align="center">
  <a aria-label="license" href="https://github.com/htunnicliff/swr-openapi/blob/main/LICENSE">
    <img alt="license" src="https://img.shields.io/github/license/htunnicliff/swr-openapi.svg?style=for-the-badge&labelColor=000000">
  </a>
  <a aria-label="npm" href="https://www.npmjs.com/package/swr-openapi">
    <img alt="npm" src="https://img.shields.io/npm/v/swr-openapi.svg?style=for-the-badge&labelColor=000000">
  </a>
  <a aria-label="npm downloads" href="https://www.npmjs.com/package/swr-openapi">
    <img alt="npm downloads" src="https://img.shields.io/npm/dm/swr-openapi?style=for-the-badge&labelColor=000000">
  </a>
</p>

## Introduction

swr-openapi is a type-safe wrapper around [`swr`](https://swr.vercel.app).

It works by using [openapi-fetch](https://openapi-ts.dev/openapi-fetch) and [openapi-typescript](https://openapi-ts.dev/introduction) 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<paths>({
  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 <div>{data.title}</div>;
}
```

## 📓 Docs

[View Docs](https://htunnicliff.github.io/swr-openapi)
