New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

auto-api-client

Package Overview
Dependencies
Maintainers
1
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

auto-api-client

Auto-generate TypeScript API clients, React hooks, and TypeScript types from Express/Fastify routes. Save 4-6 hours per project. Zero configuration required. Supports JavaScript and TypeScript. Generate React Query hooks automatically.

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
1
Created
Source

🚀 Auto API Client

Automatically generate TypeScript API clients and React hooks from your Express/Fastify server routes. Save hours of manual coding!

npm version npm downloads License: MIT

Auto-generate TypeScript API clients, React Query hooks, and TypeScript types from Express/Fastify routes. Zero configuration. Supports JavaScript and TypeScript. Save 4-6 hours per project.

🎯 Why Use This Package?

The Problem You Face Every Day

Without this package, you waste 4-6 hours per project writing repetitive API client code:

// ❌ You manually write this for EVERY route (2-3 hours)
const api = {
  async getUsers() {
    const response = await fetch('http://localhost:3000/users');
    if (!response.ok) throw new Error('Failed');
    return response.json();
  },
  async getUserById(id: number) {
    const response = await fetch(`http://localhost:3000/users/${id}`);
    if (!response.ok) throw new Error('Failed');
    return response.json();
  },
  // ... repeat for 10+ routes 😫
};

// ❌ You manually write React hooks (1-2 hours)
function useGetUsers() {
  return useQuery({
    queryKey: ['users'],
    queryFn: () => api.getUsers()
  });
}
// ... more hooks 😫

// ❌ You manually write TypeScript types (30 min)
interface User { id: number; name: string; }
// ... more types 😫

Problems:

  • Waste 4-6 hours per project on boilerplate
  • 🐛 Error-prone - Typos, wrong HTTP methods
  • 🔄 Out of sync - Frontend breaks when backend changes
  • 😫 Repetitive - Same code copy-pasted 100 times

The Solution: One Command, Everything Generated

With this package, save 4-6 hours with one command:

auto-api-client generate --entry app.js --output ./api

Result: Everything auto-generated in 30 seconds! ✅

// ✅ Auto-generated - Ready to use!
import { useGetUsers, useCreateUser } from './api/hooks';

function UsersList() {
  const { data, isLoading } = useGetUsers();
  const createUser = useCreateUser();
  // That's it! No manual code needed. 🎉
}

Benefits:

  • 30 seconds instead of 4-6 hours
  • Always correct - Auto-generated, no typos
  • 🔄 Always in sync - Regenerate when routes change
  • 🎯 Type-safe - Full TypeScript support
  • 🚀 React ready - Hooks generated automatically

📊 Time Saved

TaskWithout PackageWith PackageTime Saved
Write API client2-3 hours30 seconds2-3 hours
Write React hooks1-2 hours0 seconds1-2 hours
Write TypeScript types30 min0 seconds30 minutes
Update on changes30-60 min30 seconds30-60 min
Total (10 routes)4-6 hours30 seconds4-6 hours saved!

For 10 projects/year: Save 40-60 hours of development time! 💰

📦 Installation

# Install globally
npm install -g auto-api-client

# Or use npx (no install needed)
npx auto-api-client generate

🚀 Quick Start

Step 1: Generate Client from Your Routes

Point to your Express/Fastify entry file (supports both .js and .ts):

# For JavaScript
auto-api-client generate --entry app.js --output ./frontend/src/api

# For TypeScript
auto-api-client generate --entry server.ts --output ./frontend/src/api

Step 2: Use Generated Client

import { ApiClient } from './api/client';

const client = new ApiClient('https://api.example.com');

// Use the generated methods
const users = await client.getUsers();
const user = await client.getUserById({ id: 123 });
await client.createUser({ body: { name: 'John', email: 'john@example.com' } });

Step 3: Use React Hooks

import { useGetUsers, useCreateUser } from './api/hooks';

function UsersList() {
  const { data: users, isLoading, error } = useGetUsers();
  const createUser = useCreateUser();

  const handleCreate = async () => {
    await createUser.mutateAsync({
      body: { name: 'John', email: 'john@example.com' }
    });
  };

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

  return (
    <div>
      {users?.map(user => (
        <div key={user.id}>{user.name}</div>
      ))}
      <button onClick={handleCreate}>Add User</button>
    </div>
  );
}

📖 Complete Example

Backend (Express - JavaScript or TypeScript)

// app.js or app.ts
const express = require('express');
const app = express();

app.use(express.json());

// GET routes
app.get('/users', (req, res) => {
  res.json([{ id: 1, name: 'John Doe', email: 'john@example.com' }]);
});

app.get('/users/:id', (req, res) => {
  res.json({ id: parseInt(req.params.id), name: 'John Doe' });
});

// POST routes
app.post('/users', (req, res) => {
  res.json({ id: Date.now(), ...req.body });
});

// PUT routes
app.put('/users/:id', (req, res) => {
  res.json({ id: parseInt(req.params.id), ...req.body });
});

// DELETE routes
app.delete('/users/:id', (req, res) => {
  res.status(204).send();
});

app.listen(3000);

Generate Client

auto-api-client generate \
  --entry app.js \
  --output ./frontend/src/api \
  --base-url "http://localhost:3000"

Generated Files

The tool generates 3 files automatically:

  • client.ts - TypeScript API client class
  • types.ts - TypeScript type definitions
  • hooks.ts - React hooks (React Query)

Use in Frontend

// frontend/src/components/Users.tsx
import { useGetUsers, useCreateUser } from '../api/hooks';

export function Users() {
  const { data: users, isLoading } = useGetUsers();
  const createUser = useCreateUser();

  return (
    <div>
      <h1>Users</h1>
      {isLoading ? (
        <div>Loading...</div>
      ) : (
        users?.map(user => (
          <div key={user.id}>{user.name}</div>
        ))
      )}
      <button onClick={() => createUser.mutateAsync({ body: { name: 'New User' } })}>
        Add User
      </button>
    </div>
  );
}

🛠️ CLI Options

auto-api-client generate [options]

Options:
  -e, --entry <file>        Entry point file (app.js, server.ts, etc.)
  -o, --output <dir>        Output directory (default: ./generated)
  -u, --base-url <url>      Base URL for API (default: process.env.API_URL || "http://localhost:3000")
  -f, --framework <type>    Framework: express|fastify (default: express)
  -n, --client-name <name>  Client class name (default: ApiClient)
  -l, --hooks-library <lib> React hooks library: react-query|swr|custom (default: react-query)
  --no-hooks                Skip generating React hooks
  --no-types                Skip generating TypeScript types
  -h, --help                Display help

🔄 Watch Mode

Automatically regenerate when routes change:

auto-api-client watch --entry app.js --output ./frontend/src/api

Perfect for development! Every time you add/modify a route, the client regenerates automatically.

💻 Programmatic Usage

import { RouteScanner, ClientGenerator } from 'auto-api-client';

// Scan routes (works with both .js and .ts files)
const scanner = new RouteScanner();
const routes = await scanner.scanRoutes('./app.js', 'express');
// or
const routes = await scanner.scanRoutes('./server.ts', 'express');

// Generate client
const generator = new ClientGenerator({
  outputDir: './generated',
  baseUrl: 'https://api.example.com',
  generateHooks: true,
  hooksLibrary: 'react-query',
});

await generator.generate(routes);

🎨 Supported Route Patterns

Works with both JavaScript and TypeScript! Recognizes:

// Express (JS or TS)
app.get('/users', handler);
app.post('/users', handler);
router.get('/users/:id', handler);

// Fastify (JS or TS)
fastify.get('/users', handler);
fastify.post('/users', handler);

📁 Generated File Structure

output/
├── client.ts    # API client class with all methods
├── types.ts      # TypeScript type definitions
└── hooks.ts      # React hooks (if --no-hooks not used)

⚡ Features

  • Zero Configuration - Works out of the box
  • JavaScript & TypeScript - Supports both .js and .ts files
  • Type Safe - Full TypeScript support
  • Auto-Detection - Finds routes automatically
  • React Integration - Generates hooks for React Query/SWR
  • Watch Mode - Auto-regenerate on changes
  • Multiple Frameworks - Express & Fastify support
  • Path Parameters - Auto-detects :id params
  • Query Parameters - Detects query string params
  • Request/Response Types - Generates TypeScript types

🎯 Perfect For

  • Full-Stack Developers - Express + React projects
  • Backend Teams - Sharing APIs with frontend
  • Startups - Fast iteration, no time to waste
  • Agencies - Multiple projects, same problem
  • Anyone - Tired of writing API clients manually

📊 Real-World Impact

For Individual Developer

  • Per Project: Saves 4-6 hours of manual coding
  • Per Year (10 projects): Saves 40-60 hours
  • Prevents: 100-200 bugs from typos/errors

For Team

  • Faster Development - More time for features
  • Fewer Bugs - Auto-generated = fewer errors
  • Better Collaboration - Backend changes don't break frontend
  • Less Maintenance - Regenerate instead of manual updates

🔧 Advanced Usage

Custom Base URL per Environment

import { ApiClient } from './api/client';

const getBaseUrl = () => {
  if (process.env.NODE_ENV === 'production') {
    return 'https://api.myapp.com';
  }
  return 'http://localhost:3000';
};

export const apiClient = new ApiClient(getBaseUrl());

Error Handling

import { ApiClient } from './api/client';

const api = new ApiClient('https://api.example.com');

try {
  const user = await api.getUserById({ id: 123 });
} catch (error) {
  if (error.message.includes('404')) {
    console.log('User not found');
  } else {
    console.error('Error:', error);
  }
}

Custom Headers (Authentication)

// Extend the client class
class AuthenticatedApiClient extends ApiClient {
  async request<T>(method: string, path: string, options?: any): Promise<T> {
    const token = localStorage.getItem('token');
    return super.request<T>(method, path, {
      ...options,
      headers: {
        ...options?.headers,
        Authorization: `Bearer ${token}`,
      },
    });
  }
}

const api = new AuthenticatedApiClient('https://api.example.com');

📝 Package.json Script

Add to your package.json:

{
  "scripts": {
    "generate-api": "auto-api-client generate --entry app.js --output ./frontend/src/api"
  }
}

Then run:

npm run generate-api

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT

🙏 Acknowledgments

Built for developers who are tired of writing API clients manually.

Stop writing API clients manually. Start generating them automatically. 🚀

🔍 Search Keywords

This package helps with: API client generator, TypeScript API client, React hooks generator, Express API client, Fastify API client, auto generate API client, TypeScript SDK generator, React Query hooks generator, REST API client, API wrapper generator, code generation, boilerplate reduction, fullstack development, monorepo API client, backend to frontend, API client from routes, Express routes to TypeScript, auto generate React hooks, TypeScript types generator.

  • Full-stack developers building Express + React apps
  • Backend teams sharing APIs with frontend teams
  • Startups needing fast API client generation
  • Agencies working on multiple projects
  • Developers tired of writing repetitive API code
  • Teams using monorepo architecture
  • Projects requiring type-safe API clients

Made with ❤️ for the Node.js community

Keywords

api

FAQs

Package last updated on 10 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts