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.

1 min readTypeScriptOpenAPIDX

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:

  1. Eliminate runtime type errors - The generated types always match the API
  2. Improve DX - Full autocomplete and type checking in your IDE
  3. Reduce maintenance - Regenerate types when the API changes
  4. Increase confidence - Compile-time errors catch issues before deployment

Our Approach at Semfi

At Semfi, we built a custom NX plugin that:

  1. Watches for changes to OpenAPI specs
  2. Generates TypeScript SDKs using @hey-api/openapi-ts
  3. Creates @tanstack/react-query hooks for each endpoint
  4. 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.