Skip to main content
Apicentric can generate client-side code from your service definitions, including TypeScript types, React Query hooks, and exports to OpenAPI and Postman formats. This eliminates manual typing and keeps your frontend code in sync with API contracts.

What is code generation?

Code generation transforms your YAML service definitions into production-ready client code. Instead of manually writing types and API client code, Apicentric analyzes your endpoint definitions and generates type-safe interfaces and hooks.

Available generators

  • TypeScript types - Interface definitions for requests and responses
  • React Query hooks - Type-safe hooks for data fetching
  • OpenAPI export - Convert to OpenAPI 3.0 specification
  • Postman export - Generate Postman collection files

Why use code generation?

Type safety

Catch errors at compile time with TypeScript interfaces generated from your API definitions.

Consistency

Single source of truth ensures frontend and mock API stay synchronized.

Productivity

Stop writing boilerplate. Generate hooks and types in seconds.

Documentation

Export to OpenAPI for automatic API documentation and client SDK generation.

TypeScript type generation

Generate TypeScript interfaces from your service definitions.

Basic usage

apicentric simulator generate-types --file user-api.yaml --output types.ts

Example output

Given this service definition:
user-api.yaml
name: User API
version: "1.0"
server:
  port: 9001

endpoints:
  - method: GET
    path: /users/{id}
    responses:
      200:
        body: |
          {
            "id": {{params.id}},
            "name": "John Doe",
            "email": "[email protected]",
            "role": "admin"
          }

  - method: POST
    path: /users
    request_body:
      body: |
        {
          "name": "string",
          "email": "string",
          "role": "string"
        }
    responses:
      201:
        body: |
          {
            "id": 123,
            "name": "string",
            "email": "string",
            "role": "string"
          }
Apicentric generates:
types.ts
/**
 * Generated by Apicentric
 * Service: User API v1.0
 */

// GET /users/{id}
export interface User {
  id: number;
  name: string;
  email: string;
  role: string;
}

export interface GetUserByIdParams {
  id: string;
}

// POST /users
export interface CreateUserRequest {
  name: string;
  email: string;
  role: string;
}

export interface CreateUserResponse {
  id: number;
  name: string;
  email: string;
  role: string;
}

// API Client
export interface UserApiClient {
  getUserById(params: GetUserByIdParams): Promise<User>;
  createUser(body: CreateUserRequest): Promise<CreateUserResponse>;
}

Using generated types

import { User, CreateUserRequest } from './types';

// Type-safe API calls
const user: User = await fetch('/api/users/123').then(r => r.json());

const newUser: CreateUserRequest = {
  name: 'Alice Johnson',
  email: '[email protected]',
  role: 'developer'
};

React Query hook generation

Generate React Query hooks for seamless data fetching in React applications.

Basic usage

apicentric simulator generate-query --file user-api.yaml --output hooks.ts

Example output

From the same service definition, Apicentric generates:
hooks.ts
/**
 * Generated by Apicentric
 * Service: User API v1.0
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

// Types
export interface User {
  id: number;
  name: string;
  email: string;
  role: string;
}

export interface CreateUserRequest {
  name: string;
  email: string;
  role: string;
}

// API base URL
const API_BASE = 'http://localhost:9001';

// GET /users/{id}
export function useGetUserById(id: string) {
  return useQuery({
    queryKey: ['users', id],
    queryFn: async () => {
      const response = await fetch(`${API_BASE}/users/${id}`);
      if (!response.ok) throw new Error('Failed to fetch user');
      return response.json() as Promise<User>;
    },
  });
}

// POST /users
export function useCreateUser() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (data: CreateUserRequest) => {
      const response = await fetch(`${API_BASE}/users`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
      if (!response.ok) throw new Error('Failed to create user');
      return response.json() as Promise<User>;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
  });
}

Using generated hooks

UserProfile.tsx
import { useGetUserById, useCreateUser } from './hooks';

function UserProfile({ userId }: { userId: string }) {
  const { data: user, isLoading, error } = useGetUserById(userId);
  const createUser = useCreateUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h1>{user.name}</h1>
      <p>{user.email}</p>
      <p>Role: {user.role}</p>
    </div>
  );
}

function CreateUserForm() {
  const createUser = useCreateUser();

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    createUser.mutate({
      name: 'Bob Smith',
      email: '[email protected]',
      role: 'user',
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
      <button type="submit" disabled={createUser.isPending}>
        {createUser.isPending ? 'Creating...' : 'Create User'}
      </button>
    </form>
  );
}

Export formats

Export your service definitions to industry-standard formats.

OpenAPI export

Convert to OpenAPI 3.0 specification:
apicentric simulator export --file user-api.yaml --output openapi.json --format openapi
Generated OpenAPI:
openapi.json
{
  "openapi": "3.0.0",
  "info": {
    "title": "User API",
    "version": "1.0",
    "description": "Generated from Apicentric service definition"
  },
  "servers": [
    {
      "url": "http://localhost:9001"
    }
  ],
  "paths": {
    "/users/{id}": {
      "get": {
        "operationId": "getUserById",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "required": true,
            "schema": { "type": "string" }
          }
        ],
        "responses": {
          "200": {
            "description": "Successful response",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "id": { "type": "number" },
                    "name": { "type": "string" },
                    "email": { "type": "string" },
                    "role": { "type": "string" }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
Use OpenAPI exports for:
  • Swagger UI documentation
  • Client SDK generation (with tools like OpenAPI Generator)
  • API gateway configuration
  • Third-party integrations

Postman export

Generate Postman collections:
apicentric simulator export --file user-api.yaml --output collection.json --format postman
Import the generated collection into Postman for:
  • Manual API testing
  • Team collaboration
  • Collection runner automation
  • Documentation generation

Advanced options

Custom base URL

Override the API base URL in generated code:
apicentric simulator generate-query \
  --file user-api.yaml \
  --output hooks.ts \
  --base-url https://api.production.com

Multiple services

Generate code from multiple services:
# Generate types for all services
for file in services/*.yaml; do
  apicentric simulator generate-types \
    --file "$file" \
    --output "generated/$(basename "$file" .yaml)-types.ts"
done

Watch mode

Automatically regenerate on file changes:
# Using a file watcher like entr
ls services/*.yaml | entr apicentric simulator generate-types --file _ --output types.ts

Integration workflows

Development workflow

1

Define your API

Create or update a service YAML file:
# services/user-api.yaml
name: User API
# ... endpoint definitions
2

Generate code

Run code generation:
apicentric simulator generate-types --file services/user-api.yaml --output src/types/user-api.ts
apicentric simulator generate-query --file services/user-api.yaml --output src/hooks/user-api.ts
3

Use in your app

Import and use generated code:
import { useGetUserById } from './hooks/user-api';

const { data } = useGetUserById('123');
4

Iterate

When you update the service definition, regenerate code and TypeScript will catch any breaking changes.

CI/CD integration

.github/workflows/codegen.yml
name: Generate API Code

on:
  push:
    paths:
      - 'services/**/*.yaml'

jobs:
  generate:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v3
      
      - name: Install Apicentric
        run: npm install -g apicentric
      
      - name: Generate TypeScript types
        run: |
          apicentric simulator generate-types \
            --file services/user-api.yaml \
            --output src/types/user-api.ts
      
      - name: Generate React Query hooks
        run: |
          apicentric simulator generate-query \
            --file services/user-api.yaml \
            --output src/hooks/user-api.ts
      
      - name: Commit generated code
        run: |
          git config user.name "GitHub Actions"
          git config user.email "[email protected]"
          git add src/types src/hooks
          git commit -m "chore: regenerate API code" || exit 0
          git push

Commands reference

Generate TypeScript types

apicentric simulator generate-types --file <SERVICE.yaml> --output <FILE.ts>
Generate TypeScript interface definitions.

Generate React Query hooks

apicentric simulator generate-query --file <SERVICE.yaml> --output <FILE.ts> [--base-url <URL>]
Generate React Query hooks with optional custom base URL.

Export to OpenAPI

apicentric simulator export --file <SERVICE.yaml> --output <FILE.json> --format openapi
Convert service definition to OpenAPI 3.0 specification.

Export to Postman

apicentric simulator export --file <SERVICE.yaml> --output <FILE.json> --format postman
Generate Postman collection file.

Tips and best practices

Commit generated code to version control so team members can see when API contracts change in pull requests.
Use code generation in pre-commit hooks to ensure generated code is always up to date.
Generated React Query hooks assume you have @tanstack/react-query installed. Install it with:
npm install @tanstack/react-query
Don’t manually edit generated files - they will be overwritten. Put customizations in separate files.

Next steps

  • Set up API simulator services to generate code from
  • Use contract testing to validate generated types
  • Integrate with the TUI for visual code generation
  • Connect MCP to let AI generate service definitions

Build docs developers (and LLMs) love