Skip to content

πŸ“¦ A minimalist, copy-paste template for building type-safe API clients with Zod validation

License

Notifications You must be signed in to change notification settings

DarkPhoenix2704/openapi-zod-swagger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Type-Safe API Client Template

A copy-paste template for creating strongly-typed API clients with built-in request/response validation.

Features

  • πŸ”’ Type-safe API calls
  • βœ… Request and response validation using Zod schemas
  • πŸ“¦ Version-aware API routing
  • πŸ”„ Automatic response parsing
  • πŸ› οΈ Built on Axios for reliable HTTP requests
  • 🎯 Resource-based route organization

Usage

1. Copy the Required Files

Copy the following structure to your project:

src/
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ index.ts
β”‚   └── v1/
β”‚       └── users/
β”‚           β”œβ”€β”€ index.ts
β”‚           └── schema.ts
β”œβ”€β”€ core/
β”‚   β”œβ”€β”€ registry.ts
β”‚   └── types.ts
└── index.ts

2. Install Dependencies

npm install axios zod
# or
yarn add axios zod

3. Initialize Client

import { createApiClient } from './path-to/api-client';

// Create an API client instance
const api = createApiClient({
  baseURL: 'https://api.example.com',
  headers: {
    'Authorization': 'Bearer your-token'
  }
});

4. Use the Client

// Example: List users
async function getUsers() {
  try {
    const response = await api.v1.users.listUsers(
      undefined, // params
      { limit: 10, offset: 0 } // query
    );
    console.log(response.data);
  } catch (error) {
    console.error('Failed to fetch users:', error);
  }
}

Adding New Routes

1. Create Schema File

// src/api/v1/posts/schema.ts
import { z } from 'zod';

export const postSchema = z.object({
  id: z.string(),
  title: z.string(),
  content: z.string(),
  authorId: z.string()
});

export const createPostSchema = postSchema.omit({
  id: true
});

2. Create Route File

// src/api/v1/posts/index.ts
import Registry from '../../../core/registry';
import { postSchema, createPostSchema } from './schema';
import { z } from 'zod';

export function registerPostRoutes(registry: Registry) {
  registry.register({
    name: 'createPost',
    method: 'POST',
    version: 'v1',
    path: '/v1/posts',
    description: 'Create a new post',
    request: {
      body: createPostSchema
    },
    responses: {
      201: {
        description: 'The created post',
        schema: postSchema
      }
    },
    tags: ['posts']
  });
}

3. Register Routes

// src/api/index.ts
import { registerUserRoutes } from './v1/users';
import { registerPostRoutes } from './v1/posts';
import Registry from "../core/registry";

export function registerRoutes(registry: Registry) {
    registerUserRoutes(registry);
    registerPostRoutes(registry);
}

Current Limitations

  • Native type inference is not yet complete and work in progress
  • Response types must be explicitly defined
  • No built-in support for file uploads
  • Limited error type definitions

Configuration

The client accepts Axios request config options:

const api = createApiClient({
  baseURL: 'https://api.example.com',
  timeout: 5000,
  headers: {
    'Authorization': 'Bearer token'
  }
});

Error Handling

try {
  const users = await api.v1.users.listUsers();
} catch (error) {
  if (error instanceof z.ZodError) {
    // Handle validation error
    console.error('Response validation failed:', error.errors);
  } else {
    // Handle other errors (network, etc.)
    console.error('Request failed:', error);
  }
}

Customization

You can modify the core files to add additional functionality:

  • Add middleware support in registry.ts
  • Extend error handling in the request function
  • Add custom validation rules to schemas
  • Implement caching mechanisms
  • Add request/response interceptors

Contributing

This is a template library - fork it and customize it for your needs! Feel free to share improvements through issues and pull requests.

License

MIT License

About

πŸ“¦ A minimalist, copy-paste template for building type-safe API clients with Zod validation

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published