Skip to content

Generating API Clients

NotNexx edited this page Feb 24, 2025 · 1 revision

πŸ”— Generating API Clients

Simple API Router allows you to automatically generate a frontend API client that connects to your backend. This makes it easier to consume your API without manually writing fetch calls.

πŸš€ Generate an API Client

To generate an API client for your backend, run the following command:

npx n-sar export-routes http://localhost:3000

This command:

  • Scans all registered API routes.
  • Generates an apiClient.js file.
  • Provides ready-to-use functions for calling your API.

πŸ“‚ API Client Structure

After running the export command, you'll find the apiClient.js file in your project:

my-project/
β”œβ”€β”€ apiClient.js
β”œβ”€β”€ api/
β”‚   β”œβ”€β”€ user.js
β”‚   β”œβ”€β”€ product.js
└── server.js

πŸ› οΈ Using the API Client in Your Frontend

Once the client is generated, you can import and use it in your frontend:

import APIClient from './apiClient';

// Example: Fetch user data
APIClient.user_get().then(response => {
    console.log(response);
});

// Example: Create a new user
APIClient.user_post({ name: "John Doe" }).then(response => {
    console.log(response);
});

Each function is named based on the API route and method:

  • user_get() β†’ Calls GET /user
  • user_post(data) β†’ Calls POST /user
  • product_get() β†’ Calls GET /product
  • And so on...

βš™οΈ Customizing the API Client

By default, the generated client assumes your API is hosted at http://localhost:3000.
You can modify the base URL in apiClient.js:

const BASE_URL = "https://api.yourdomain.com";

Alternatively, you can specify the base URL during export:

npx n-sar export-routes https://api.yourdomain.com

This ensures all requests go to the correct API endpoint.


πŸ“– Next Steps

πŸ’‘ Need help? Open an [issue](../issues) or join the [discussions](../discussions).