-
Notifications
You must be signed in to change notification settings - Fork 0
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.
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.
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
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()
β CallsGET /user
-
user_post(data)
β CallsPOST /user
-
product_get()
β CallsGET /product
- And so on...
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.
-
Learn how to [use the package](Usage).
-
Want to contribute? Check out the [Contributing](Contributing) guide.
π‘ Need help? Open an [issue](../issues) or join the [discussions](../discussions).