Fetching Data from APIs
Fetching Data from APIs — why it matters
fetch makes an HTTP request and returns a Promise<Response>. A fulfilled fetch does not automatically mean the HTTP status is successful: check response.ok. Calling response.json() produces an unknown runtime value whose shape should be validated before trusted use. For a self-contained example, fetch a data: URL with JSON to exercise the same response API.
What you’ll learn
- Explain fetching data from apis and the problem it solves.
- Identify the relevant compile-time checks and runtime responsibilities.
- Run the example, predict its output, and try a realistic modification.
Understand the mechanism
fetch resolves with a Response, then .json() parses the bytes. The runtime type guard verifies message is a string before code accesses it. No external server is required for this demonstration.
A type argument or cast does not validate response.json() payloads; use runtime checks for untrusted API data.
Follow the concept flow
Run the primary TypeScript example
Save as fetching-data-from-apis.ts. The following program passed strict TypeScript compilation, and the displayed output was captured by executing its emitted JavaScript with Node.js 22.16.0.
TypeScript source
type Notice = { message: string };
function isNotice(value: unknown): value is Notice {
return typeof value === "object" && value !== null && "message" in value && typeof value.message === "string";
}
async function main(): Promise<void> {
const response = await fetch('data:application/json,%7B%22message%22%3A%22Ready%22%7D');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data: unknown = await response.json();
if (!isNotice(data)) throw new Error("Unexpected JSON");
console.log(data.message);
}
main().catch(console.error);Verified output
ReadyCompile: npx tsc --strict --target es2022 --module commonjs fetching-data-from-apis.ts; run: node fetching-data-from-apis.js. For Node.js API examples, install @types/node first. For browser projects, use the browser-specific instructions below.
The example runs in Node.js 22.16.0; if it reads runtime environment details, your displayed values may differ.
Trace the result
fetch resolves with a Response, then .json() parses the bytes. The runtime type guard verifies message is a string before code accesses it. No external server is required for this demonstration.
Predict what changes if you alter one input. Then run the code to compare your reasoning with the real output.
Build the real browser interaction
Real browser lab: This TypeScript targets actual DOM APIs and was successfully type-checked against the DOM library. It requires a browser; its runtime interaction was not simulated in Node.js. Save the two files together, compile the TypeScript, and serve this folder through a local HTTP server such as python3 -m http.server 8000 (especially important for modules and workers).
index.html
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><title>TypeScript browser lab</title></head><body>
<h1 id="title">TypeScript lesson</h1><button id="action">Run</button><p id="output"></p>
<script type="module" src="./app.js"></script>
</body></html>app.ts
type Notice = { message: string };
async function load(): Promise<void> {
const response = await fetch('data:application/json,%7B%22message%22%3A%22Ready%22%7D');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const value: unknown = await response.json();
if (typeof value !== "object" || value === null || !("message" in value) || typeof value.message !== "string") throw new Error("Invalid data");
const output = document.querySelector<HTMLElement>("#output");
if (output) output.textContent = value.message;
}
load().catch(error => console.error(error));Compile: npx tsc --strict --target es2022 --module es2022 --lib es2022,dom app.ts. For the worker example also compile worker.ts with --lib es2022,webworker. Then open the served HTML page in a browser to interact with it.
Common mistake and correction
A type argument or cast does not validate response.json() payloads; use runtime checks for untrusted API data.
Identify whether the failure is a type-checking issue, a configuration issue, or a runtime behavior issue before choosing a fix.
Practice the concept
Change the JSON to include an id field and update the runtime type guard before displaying it.
Write down your expected result first. For configuration examples, compare compiler output and diagnostics; for test examples, make the assertion fail deliberately to verify that the tool reports it.
Check your understanding
What to remember
fetch makes an HTTP request and returns a Promise<Response>.
Run the primary example, then complete the practice task or environment-specific lab.
Reaching the recap and completing the quizzes are separate milestones.