Practical API Tutorial
Connect an AI-Built Frontend to a Mock API
AI app builders get a working interface on screen fast, but the data usually ends up hard-coded inside components. Move it to a hosted mock API so the app fetches real HTTP responses, handles loading and errors, and is ready for your production backend.
No account needed to try. A free account keeps your project.
Why this matters
Hard-coded data works until it doesn't
Tools such as Lovable, Bolt, v0 and Cursor often put sample data straight into the component that displays it:
// What AI tools often generate: the data lives inside the component
const products = [
{ id: 1, name: "Wireless Headphones", price: 79.99 },
{ id: 2, name: "Mechanical Keyboard", price: 109.99 },
];
export function ProductList() {
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}That looks finished, but it hides three problems:
- There is no loading or error state, because nothing is ever fetched.
- The data shape is decided by the component rather than by an API contract, so it often breaks when the real backend arrives.
- Every screen has its own copy of the data, so changes have to be made in several places.
Create the endpoint
Turn the hard-coded array into an endpoint
Copy the array out of the component and convert it to JSON. Then open the Forge API generator, choose GET, enter /products as the path, paste the JSON and generate the endpoint.
[
{ "id": 1, "name": "Wireless Headphones", "price": 79.99 },
{ "id": 2, "name": "Mechanical Keyboard", "price": 109.99 }
]You get a URL such as https://apis.getforgeapi.com/YOUR_PROJECT_KEY/products. Repeat this for each list or detail view your app shows, or launch a ready-made mock API if one matches your app.
Configure the URL
Store the base URL in an environment variable
Keep everything before the path in one variable, so the same code can call the mock API now and your real API later. The prefix depends on the framework your tool generated, which you can see in package.json: Vite projects read variables that start with VITE_, and Next.js projects read variables that start with NEXT_PUBLIC_.
VITE_API_BASE_URL=https://apis.getforgeapi.com/YOUR_PROJECT_KEYNEXT_PUBLIC_API_BASE_URL=https://apis.getforgeapi.com/YOUR_PROJECT_KEYWhat each tool's own documentation says:
| Tool | What its documentation says | Variable to use |
|---|---|---|
| Lovable | Browser variables use the VITE_ prefix and live in the project's .env file, which Lovable says to commit rather than add to .gitignore. Its Secrets are for server-side code only. | VITE_API_BASE_URL in .env |
| Bolt | Environment variables go in a .env file or Bolt's Secrets menu. Its help pages do not name a prefix. | Check package.json: VITE_ for Vite, NEXT_PUBLIC_ for Next.js |
| v0 | Projects default to Next.js. Browser code can only read variables that start with NEXT_PUBLIC_, and each project has its own environment variables. | NEXT_PUBLIC_API_BASE_URL |
| Cursor or any editor | It is your own codebase, so your framework's normal rules apply. | VITE_ for Vite, NEXT_PUBLIC_ for Next.js |
From the Lovable, Bolt and v0 documentation, checked on 1 December 2026. These tools change quickly, so check their docs if a menu has moved.
These variables are public
VITE_ and NEXT_PUBLIC_ values are written into the JavaScript sent to the browser. A mock API URL is fine there. Never put API keys, passwords or database credentials in them.
Ask the AI
Have your AI tool replace the hard-coded data
Give your tool a precise instruction. Vague prompts such as "connect to the API" often produce a new backend or a database you do not need. This prompt keeps the change small:
Move the hard-coded product data out of this app and load it from an API.
- The API base URL is in an environment variable: VITE_API_BASE_URL
(use NEXT_PUBLIC_API_BASE_URL instead if this is a Next.js project).
- GET {base URL}/products returns the same JSON array as the current data.
- Create one small fetch helper in src/lib/api.ts that throws an error with
the HTTP status when response.ok is false.
- In the component, show a loading message, an error message with a
"Try again" button, an empty state, and the list.
- Keep the existing types, field names and styling. Do not add a backend,
a database or any API keys.The result should look roughly like this: one helper that turns failed responses into errors, and a component that handles every state.
// src/lib/api.ts
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;
export class ApiError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
this.name = "ApiError";
}
}
export async function getJson<T>(path: string, signal?: AbortSignal): Promise<T> {
const response = await fetch(`${API_BASE_URL}${path}`, { signal });
if (!response.ok) {
const body = await response.json().catch(() => null);
throw new ApiError(
response.status,
body?.error?.message ?? `Request failed with status ${response.status}`,
);
}
return (await response.json()) as T;
}// In a Next.js project, read the URL like this instead:
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL;// src/components/ProductList.tsx
import { useEffect, useState } from "react";
import { ApiError, getJson } from "../lib/api";
type Product = {
id: number;
name: string;
price: number;
};
export function ProductList() {
const [products, setProducts] = useState<Product[] | null>(null);
const [error, setError] = useState("");
const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
const controller = new AbortController();
setProducts(null);
setError("");
getJson<Product[]>("/products", controller.signal)
.then(setProducts)
.catch((caught: unknown) => {
if (controller.signal.aborted) return;
setError(
caught instanceof ApiError && caught.status === 404
? "We could not find any products."
: "Something went wrong. Please try again.",
);
});
return () => controller.abort();
}, [reloadKey]);
if (error) {
return (
<div role="alert">
<p>{error}</p>
<button type="button" onClick={() => setReloadKey((key) => key + 1)}>
Try again
</button>
</div>
);
}
if (!products) return <p role="status">Loading products…</p>;
if (products.length === 0) return <p>No products yet.</p>;
return (
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name} — ${product.price.toFixed(2)}
</li>
))}
</ul>
);
}Check the result in the browser's network panel: you should see a request to apis.getforgeapi.com returning your JSON.
Test failures
Make the app handle errors before your users find them
Create two more endpoints: GET /products-missing with status 404 and GET /products-error with status 500. Then ask your tool to handle them:
Add handling for API failures to the product list:
- 404 from GET /products-missing: show "We could not find any products."
- 500 from GET /products-error: show "Something went wrong" and a retry button.
- Never show raw error objects or stack traces to the user.
Temporarily point the list at each path so I can check every state, then
switch it back to /products.For a complete approach, see how to test API error responses and simulate slow API responses.
Go to production
Switch to your real backend
When the real API serves the same paths and JSON shapes, only the environment variable changes:
Our real backend is ready at https://api.example.com. It serves the same
paths and JSON shapes as the mock API. Update the environment variable for
production builds only, and do not change any component code.What a mock API does not do
Each endpoint returns the response you configured. A POST does not add an item to a later GET, and there is no login or database behind it. Use it to build and test the interface, then replace it with your real backend.
Frequently asked questions
AI-built frontends and mock APIs
Do I need a Forge API account to try this?
No. Generate an endpoint from the Forge API homepage and you get a temporary demo project that lasts 12 hours. Create a free account within that time to keep it.
Will the endpoints work from Lovable, Bolt or v0 previews?
Yes. Forge API endpoints allow cross-origin requests from any website, so the browser can call them from a preview URL, your local dev server or a deployed app.
Lovable says external API calls should run server-side. Does that apply here?
That advice is about keeping API keys out of the browser. Forge API mock endpoints need no key, so calling them from frontend code is fine. Never put real secrets in VITE_ or NEXT_PUBLIC_ variables, because their values are included in the code sent to the browser.
Is it safe to put the mock API URL in frontend code?
The URL is not a secret: anyone who has it can call the endpoints. Keep mock responses free of real personal or sensitive data.
What changes when my real backend is ready?
Only the base URL, as long as the real API serves the same paths and JSON shapes. Set the environment variable to the production URL for production builds and the components keep working.
Give your AI-built app a real API
Paste your hard-coded data into the generator and get a hosted endpoint in seconds. No account needed to try it.