Skip to main content

Building Type-Safe APIs with OpenAPI and Code Generation

How code generation from OpenAPI specs can eliminate runtime errors and improve developer productivity.

January 15, 2025
8 min read
TypeScriptOpenAPIDX

The Problem with Manual API Typing

When working with REST APIs in TypeScript, we often manually create types based on API documentation. This approach has several issues:

  • Documentation drift: API docs get out of sync with the actual implementation
  • Human error: Typos and incorrect types slip through
  • Maintenance burden: Every API change requires manual type updates
  • Incomplete coverage: Edge cases and error responses often get missed
  • Enter Code Generation

    By generating TypeScript types directly from OpenAPI specifications, we can:

  • Eliminate runtime type errors - The generated types always match the API
  • Improve DX - Full autocomplete and type checking in your IDE
  • Reduce maintenance - Regenerate types when the API changes
  • Increase confidence - Compile-time errors catch issues before deployment
  • Our Approach at Semfi

    At Semfi, we built a custom NX plugin that:

  • Watches for changes to OpenAPI specs
  • Generates TypeScript SDKs using @hey-api/openapi-ts
  • Creates @tanstack/react-query hooks for each endpoint
  • Keeps the entire monorepo in sync
  • // Generated code example
    export const useGetUsers = (options?: UseQueryOptions) => {
      return useQuery({
        queryKey: ['users'],
        queryFn: () => api.getUsers(),
        ...options,
      });
    };

    Results

    After implementing this approach:

  • 100+ endpoints typed and code-generated
  • Zero runtime type errors in production
  • Faster onboarding for new team members
  • Automated SDK updates with CI/CD
  • Getting Started

    Check out my open-source plugin openapi-ts-nx-plugin to get started with automatic code generation in your NX monorepo.