Skip to main content

The Other Side of the API

TypeScript programs are not only servers — they call APIs too: fetching data, talking to services, integrating third parties. The client is fetch, built into Node.js, and three habits:

1. make the request (await fetch(url) for a GET, or fetch(url, { method, headers, body }) for full control),
2. check res.status before trusting the body — fetch does not throw on 404 or 500,
3. read the body once, with await res.json() or await res.text() — never both.

The demos below call a small local server started inside the same program, so the outputs are stable — the client code is exactly what you would point at a real URL.


GET and Decode

The everyday task: GET a URL, check the status, and turn the JSON body into data with await res.json(). That call returns any, so an as UserRecord[] tells the type checker what you expect to have.

Fetch a list into objects

The response body becomes a UserRecord[], and from there it is ordinary TypeScript data — looped and printed field by field.

Prompt
Write a TypeScript program that GETs a JSON array of users with fetch from a small local server started in the same file, checks the status code, turns the body into a UserRecord[] with await res.json(), and prints each user's id and name.
Output: TypeScript file and captured output

POST with a JSON Body

Sending data is the mirror image: stringify the object, pass it as body with the right content type — then read the server's answer, which here carries the id the server assigned.

Send an object, read the answer

The object goes out as JSON and the created record comes back with its new id 7 — the whole write path of an API client in one small program. Node.js prints the parsed object as { id: 7, name: 'Cleo' }.

Prompt
Write a TypeScript program that POSTs a new user as JSON with fetch and the application/json content type to a small local server that assigns an id and answers 201, then reads the response and prints the status and the created user with its new id.
Output: TypeScript file and captured output