Skip to main content

The Other Side of the API

Go programs are not only servers — they call APIs too: fetching data, talking to services, integrating third parties. The net/http client side is three habits:

1. make the request (http.Get, http.Post, or http.NewRequest for full control),
2. always defer resp.Body.Close(),
3. check the status code before trusting the body.

The demos below call a local test server, 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, decode the JSON straight from the body into structs with json.NewDecoder(resp.Body).Decode(&value) — no intermediate string needed.

Fetch a list into structs

The response body decodes directly into []User, and from there it is ordinary Go data — looped and printed field by field.

Prompt
Write a Go program that GETs a JSON array of users from a server (an httptest server in the demo), checks the status code, decodes the body directly into a slice of User structs with json.NewDecoder, and prints each user's id and name.
Output: Go program and captured output

POST with a JSON Body

Sending data is the mirror image: marshal the struct, wrap the bytes in a reader, POST with the right content type — then decode the server's answer, which here carries the id the server assigned.

Send a struct, read the answer

The struct goes out as JSON and the created record comes back with its new id — the complete write-path of an API client in one small program.

Prompt
Write a Go program that marshals a new User struct to JSON, POSTs it with the application/json content type to a server that assigns an id and answers 201 (an httptest server in the demo), then decodes the response and prints the status and the created user with its new id.
Output: Go program and captured output