Module 38: API Integration

Lesson 1 of 5 · 15–25 minutes

An API client and a practice server

🏠The everyday picture

Before the real shop opens, staff practise with a dummy till that behaves like the real one. When the real till arrives, they already know how to use it.

📘What it really is

const BASE = import.meta.env.VITE_API_URL ?? "http://localhost:3001";

export async function getEnquiries(): Promise<Enquiry[]> {
  const res = await fetch(`${BASE}/enquiries`);
  if (!res.ok) throw new Error(`Couldn't load enquiries (${res.status})`);
  return res.json();
}
npx json-server db.json --port 3001

with db.json holding { "enquiries": [ ... ] }. It supports GET, POST, PATCH and DELETE.

🖱️Try it

Create db.json with your sample enquiries and start json-server. Open http://localhost:3001/enquiries in the browser. Create src/api.ts with getEnquiries, getEnquiry(id), createEnquiry(data), updateEnquiry(id, changes) and deleteEnquiry(id), each checking res.ok.

✅Quick check

Why keep every API call in one api.ts file?

Show the answer

Addresses, headers and error handling are in one place; switching to a new backend changes one file.

Can you put a payment secret key in VITE_PAYMENT_KEY?

Show the answer

No. VITE_ variables are built into the frontend, which anyone can read.

← BackModule 38
ProLearners Assist