Package Exports
- auto-api-client
- auto-api-client/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (auto-api-client) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
🚀 Auto API Client
Automatically generate TypeScript API clients and React hooks from your Express/Fastify server routes. Save hours of manual coding!
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 ./apiResult: 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
| Task | Without Package | With Package | Time Saved |
|---|---|---|---|
| Write API client | 2-3 hours | 30 seconds | 2-3 hours |
| Write React hooks | 1-2 hours | 0 seconds | 1-2 hours |
| Write TypeScript types | 30 min | 0 seconds | 30 minutes |
| Update on changes | 30-60 min | 30 seconds | 30-60 min |
| Total (10 routes) | 4-6 hours | 30 seconds | 4-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/apiStep 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 classtypes.ts- TypeScript type definitionshooks.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/apiPerfect 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
.jsand.tsfiles - ✅ 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
:idparams - ✅ 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.
📈 Popular Use Cases
- 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