Skip to content

OpenAPI Integration

Nuxt API Party integrates with an OpenAPI schema to provide full type safety for your API requests. Generated types include:

  • Request path with path parameters
  • Query parameters
  • Headers
  • Request body
  • Response body
  • Error responses

Mandatory Dependency

Usage of this feature requires openapi-typescript to generate TypeScript definitions from your OpenAPI schema file. It is installed alongside Nuxt API Party.

Schema Generation

Based on your configured routes, some web frameworks can generate an OpenAPI schema for you. Some examples include:

If your framework doesn't directly support it, there may also be an additional library that does.

Configuring the Schema

Add the schema property to your endpoint config. Set it to a file path or URL of the OpenAPI schema, or an async function returning the parsed OpenAPI schema. The file can be JSON or YAML format.

The following schema is used for code examples on this page:

Details
yaml
# `schemas/myApi.yaml`
openapi: 3.0.0
info:
  title: My API
  version: 0.1.0
paths:
  /foo:
    get:
      operationId: getFoos
      responses:
        200:
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Foo'
    post:
      operationId: createFoo
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Foo'
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Foo'
  /foo/{id}:
    get:
      operationId: getFoo
      parameters:
        - name: id
          in: path
          type: number
      responses:
        200:
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Foo'
components:
  schemas:
    Foo:
      type: object
      items:
        id:
          type: number
        bar:
          type: string
      required:
        - bar

Reference the schema file in your endpoint configuration:

ts
export default defineNuxtConfig({
  apiParty: {
    myApi: {
      url: process.env.MY_API_API_BASE_URL!,
      schema: './schemas/myApi.yaml'
    }
  }
})

TIP

If the enableSchemaFileWatcher experimental option is enabled (it is by default), changes to local schema files will automatically regenerate the types. When disabled or using a remote schema, you will need to restart the Nuxt dev server to pick up changes.

Using the Types

For most use cases, no further configuration is needed. Nuxt API Party uses the generated types to infer correct types automatically when useFetch-like and $fetch-like composables are used.

However, you may want to leverage type information in additional ways.

Extract Schema Types

The exported components interface of the virtual module for your API contains all schema types defined in your OpenAPI schema. Use it to extract models for your API.

Using the schema above, extract the Foo type:

ts
import { components } from '#nuxt-api-party/myApi'

type FooModel = components['schemas']['FooModel']
//   ^? { id?: number; bar: string }

Use OpenAPI Defined Path Parameters

OpenAPI can define path parameters on endpoints. They're declared as /foo/{id}. The endpoint isn't defined as /foo/10, so using that as the path breaks type inference.

To work with path parameters, set an object of parameters to the path property. Use the declared path for type inference, and the type checker ensures you provide all required path parameters. Parameters are interpolated into the path before the request is made.

ts
const data = await $myApi('/foo/{id}', {
  path: {
    id: 10
  }
})

For reactive path parameters, pass a ref or getter function:

ts
const id = ref(10)

const data = await $myApi('/foo/{id}', {
  path: () => ({
    id: id.value
  })
})

WARNING

Issues will NOT be reported at runtime by Nuxt API Party if the wrong parameters are used. The incomplete path will be sent to the backend as-is.

Route Method Overloading

Some routes support multiple HTTP methods. The typing chooses the type based on the method property. When omitted, typing defaults to GET.

In the example schema, GET /foo will return a Foo[] array, but POST /foo will return a Foo object.

ts
const resultGet = await $myApi('/foo')
//    ^? { id?: number; bar: string }[]

const resultPost = await $myApi('/foo', {
//    ^? { id?: number; bar: string }
  method: 'POST',
  body: {
    bar: 'string'
  }
})

OpenAPI Type Helpers

Type Declarations

For more details and examples, see the OpenAPI Type Helpers documentation.

Extract types directly from your OpenAPI schema instead of writing them manually. This approach ensures types stay synchronized with your API specification and reduces the risk of type mismatches:

ts
// ❌ Manual type definition (error-prone, out of sync)
interface CreateUserRequest {
  name: string
  email: string
}

// ✅ Extract from OpenAPI schema (always up-to-date)
type CreateUserRequest = PetStore<'/user', 'post'>['request']

Nuxt API Party generates a powerful unified type interface for each service that provides comprehensive access to all endpoint information. This interface follows the pattern Service<Path, Method> and serves as your single source of truth for API type information:

ts
import type { PetStore } from '#nuxt-api-party'

// The unified interface: Service<Path, Method>
type UserEndpoint = PetStore<'/user/{username}', 'get'>

// Extract any part of the endpoint
type PathParams = UserEndpoint['path'] // { username: string }
type QueryParams = UserEndpoint['query'] // Query parameters
type RequestBody = UserEndpoint['request'] // Request body type
type Response = UserEndpoint['response'] // Success response (200)
type ErrorResponse = UserEndpoint['responses'][404] // Specific status code

Follow the OpenAPI Type Helpers documentation for more details and practical examples of using these types in your application.

Released under the MIT License.