Orval Documentation

repository·master·Indexed 27 days ago

https://github.com/orval-labs/orval

A code generation tool that creates type-safe TypeScript clients from OpenAPI v3 or Swagger v2 specifications. Orval supports a wide range of frameworks and libraries, including React (React Query, SWR), Vue (Vue Query), Svelte (Svelte Query), Angular, SolidStart, SolidQuery, Hono, Zod, Effect, Native Fetch, and Model Context Protocol (MCP).

Tokens
102.8K
Snippets
355
Records
485
Agent score
91%

What's inside Orval

  1. Overview of Orval

    master
    Orval is a tool that generates type-safe TypeScript clients from valid OpenAPI v3 or Swagger v2 specifications (in both YAML and JSON formats). It is designed to bridge the gap between API contracts and modern frontend development by providing full type safety for API responses and requests, ready-to-use HTTP request functions, and automatic mock generation using MSW.
  2. Overview of Orval Code Generation

    master
    Orval is a RESTful client generator that produces type-safe TypeScript clients from OpenAPI v3 or Swagger v2 specifications (in yaml or json formats). It can generate models, requests, hooks, mocks, and more.
  3. Generate type-safe TypeScript clients with Orval

    master
    Orval generates type-safe JavaScript (TypeScript) clients from any valid OpenAPI v3 or Swagger v2 specification provided in yaml or json formats. It is designed to integrate with React, Vue, Svelte, and Angular applications to provide type-safe Generate, valid, cache, and mock capabilities based on your OpenAPI specification.
  4. Use Angular-specific features with @orval/angular

    master

    The @orval/angular package provides several specialized features for Angular development:

    • HttpClient Overloads: Generates HttpClient observe overloads.
    • Signal Integration: Generates signal-based parameters for httpResource and provides ResourceState<T> and toResourceState() helpers.
    • Response Handling: Supports multi-content-type response branching via generated Accept helpers and provides ClientResult / ResourceResult aliases.
    • Runtime Validation: Supports Zod-backed runtime validation.
    • Resource Helpers: Provides helpers for resource options such as defaultValue, debugName, injector, and equal.
  5. Generate type-safe clients with Orval

    master

    Orval generates type-safe JavaScript/TypeScript clients from OpenAPI v3 or Swagger v2 specifications provided in yaml or json formats. It is designed to automate the generation of code for data fetching, caching, and mocking in modern frontend frameworks.

    Supported integrations include:

    • React (including React Query and SWR)
    • Vue (including Vue Query)
    • Svelte (including Svelte Query)
    • Angular
  6. Capabilities of the Orval AI Agent Skill

    master

    The orval skill provides automated assistance for the following Orval features:

    • Client Generation: Support for React, Vue, Svelte, Solid, and Angular Query, as well as SWR, Fetch, Axios, Hono, and MCP.
    • Schema & Validation: Zod schema generation and runtime validation.
    • Mocking: MSW (Mock Service Worker) mock generation including test setup patterns.
    • Server-side: Hono server handlers with response validation.
    • Advanced Patterns: Custom HTTP mutators, authentication patterns, NDJSON streaming, and programmatic API usage.
  7. Validate request bodies manually with Zod

    master

    While Orval generates Zod schemas and TypeScript types for request bodies, it does not automatically call Schema.parse(body) before sending a request. To ensure request bodies are valid before transmission, you must validate them explicitly using the generated schemas.

    const payload = CreatePetsBody.parse(formValue);
    return this.petsService.createPets(payload);
  8. Use Generated MSW Handlers in Vitest

    master

    To use generated MSW handlers in a testing environment like Vitest, import the generated .msw.ts file and pass the handlers to setupServer from msw/node.

    You can override handlers for specific tests using server.use() to simulate different scenarios, such as empty lists or dynamic responses based on request parameters.

    import {
      getListPetsMockHandler,
      getShowPetByIdMockHandler,
    } from './api/petstore.msw';
    import { setupServer } from 'msw/node';
    
    const server = setupServer(...getListPetsMockHandler());
    
    beforeAll(() => server.listen());
    afterEach(() => server.resetHandlers());
    afterAll(() => server.close());
    
    // Override for specific test
    it('handles empty list', () => {
      server.use(getListPetsMockHandler([]));
      // ...
    });
    
    // Dynamic response based on request
    it('returns pet by id', () => {
      server.use(
        getShowPetByIdMockHandler(async ({ params }) => ({
          id: Number(params.petId),
          name: 'Test Pet',
        })),
      );
      // ...
    });
  9. Configure Orval to generate Effect schemas

    master

    To use Effect schemas alongside your HTTP client (like SWR or TanStack Query) for runtime validation, you must define two separate generation targets in your orval.config.ts. One target generates the HTTP client, and a second target generates the Effect schemas.

    Important: Use the fileExtension: '.effect.ts' option in your Effect schema configuration to prevent filename conflicts with your HTTP client files.

    import { defineConfig } from 'orval';
    
    export default defineConfig({
      // HTTP client generation
      petstore: {
        input: {
          target: './petstore.yaml',
        },
        output: {
          mode: 'tags-split',
          client: 'swr',
          target: 'src/api/endpoints',
          schemas: 'src/api/models',
          mock: true,
        },
      },
      // Effect schema generation
      petstoreEffect: {
        input: {
          target: './petstore.yaml',
        },
        output: {
          mode: 'tags-split',
          client: 'effect',
          target: 'src/api/endpoints',
          fileExtension: '.effect.ts',
        },
      },
    });
  10. Run Orval via Docker

    master

    Orval 8+ requires Node.js 22.18 or newer. If your project uses an older Node LTS, you can use the official Docker image to perform code generation.

    Note: Replace ghcr.io/orval-labs/orval with orval:local when testing locally before the official image is published.

    # macOS / Linux
    docker run --rm -v "$(pwd):/app" -w /app ghcr.io/orval-labs/orval
    
    # Windows Git Bash
    MSYS_NO_PATHCONV=1 docker run --rm -v "$(pwd):/app" -w /app ghcr.io/orval-labs/orval
    
    # Windows CMD
    cd /d "C:\path\to\your-project"
    docker run --rm -v "%cd%:/app" -w /app ghcr.io/orval-labs/orval
    
    # Windows PowerShell
    cd "C:\path\to\your-project"
    docker run --rm -v "${PWD}:/app" -w /app ghcr.io/orval-labs/orval
  11. Ensure deterministic mock output

    master

    To get reproducible mock data (useful for snapshot testing), seed Faker's PRNG before invoking your factories.

    import { faker } from '@faker-js/faker';
    import { getShowPetByIdResponseMock } from './api/petstore.faker';
    
    beforeEach(() => {
      faker.seed(42);
    });
    
    it('matches snapshot', () => {
      expect(getShowPetByIdResponseMock()).toMatchSnapshot();
    });