Skip to content

Latest commit

 

History

History
125 lines (99 loc) · 3.09 KB

File metadata and controls

125 lines (99 loc) · 3.09 KB
title
openapi-vue-query

Introduction

openapi-vue-query is a type-safe tiny wrapper (1 kb) around @tanstack/vue-query to work with OpenAPI schema.

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

::: code-group

<script setup lang="ts">
import createFetchClient from "openapi-fetch";
import createClient from "openapi-vue-query";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript

const fetchClient = createFetchClient<paths>({
  baseUrl: "https://myapi.dev/v1/",
});
const $api = createClient(fetchClient);

const { data, error, isLoading } = $api.useQuery(
  "get",
  "/blogposts/{post_id}",
  {
    params: {
      path: { post_id: 5 },
    },
  }
)
</script>

<template>
  <div>
    <template v-if="isLoading || !data">
      Loading...
    </template>
    <template v-else-if="error">
      An error occurred: {{ error.message }}
    </template>
    <template v-else>
      {{ data.title }}
    </template>
  </div>
</template>

:::

Setup

Install this library along with openapi-fetch and openapi-typescript:

npm i openapi-vue-query openapi-fetch
npm i -D openapi-typescript typescript

::: tip Highly recommended

Enable noUncheckedIndexedAccess in your tsconfig.json (docs)

:::

Next, generate TypeScript types from your OpenAPI schema using openapi-typescript:

npx openapi-typescript ./path/to/api/v1.yaml -o ./src/lib/api/v1.d.ts

Basic usage

Once your types has been generated from your schema, you can create a fetch client, a vue-query client and start querying your API.

::: code-group

<script setup lang="ts">
import createFetchClient from "openapi-fetch";
import createClient from "openapi-vue-query";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript

const fetchClient = createFetchClient<paths>({
  baseUrl: "https://myapi.dev/v1/",
});
const $api = createClient(fetchClient);

const { data, error, isLoading } = $api.useQuery(
  "get",
  "/blogposts/{post_id}",
  {
    params: {
      path: { post_id: 5 },
    },
  }
)
</script>

<template>
  <div>
    <template v-if="isLoading || !data">
      Loading...
    </template>
    <template v-else-if="error">
      An error occurred: {{ error.message }}
    </template>
    <template v-else>
      {{ data.title }}
    </template>
  </div>
</template>

:::

::: tip You can find more information about createFetchClient on the openapi-fetch documentation. :::