Handling Responses¶
Contents | Previous: Request Bodies | Next: Authentication, TLS, and Proxy
View in another language — C++ · C#/.NET · Java · Kotlin · Node/TypeScript
After reading this chapter
This chapter distinguishes JSON-decoded bodies from original HTTP response data. Its code comes from each language's HttpClient tutorial.
The HTTP client changes only the response form on the same request builder. A typed response carries status, headers, and a JSON-decoded body. A raw response carries status, headers, and the body before JSON decoding. Response Rules covers status-specific handling.
1. A Typed Response Is the Default¶
A typed response is the default for a successful JSON API call. It ends as an exception when the HTTP status is 400 or higher, while a raw response preserves an error body. A terminator is the final call that submits the gathered request and selects its response form.
The response form does not change the request sent. It determines whether application code keeps status and headers or leaves only a JSON body value.
const typed = await client.get('/players/p2').submit<PlayerInfo>();
const raw = await client.get('/players/p2').submitRaw();
const fetched = await client.get('/players/p2').fetch<PlayerInfo>();
console.log(
`response kinds: typed ${typed.status} raw ${raw.headers['content-type']} fetch ${fetched.nickname}`
);
The example reads the same player response as typed, raw, and body-only values, exposing its status, content type, and nickname respectively.
2. A Raw Response Preserves HTTP Details¶
A 4xx or 5xx response is returned as a raw response when its transfer succeeds. This form supports branches based on status and access to an API error body.
The body-only terminator applies when only the body is required. It leaves only the successful JSON value in the calling flow and does not return status or headers.
Choose the response form first
A typed response fits a normal JSON API, a raw response fits direct HTTP status and error-body handling, and a body-only response fits a path that needs no other response information.
3. Compression Is Opt-in¶
A client with compression fits an API that sends compressed responses while the application consumes ordinary JSON responses. Response Rules covers the detailed behavior.
const compressed = await ZLinkHttpClient.create(clientBaseUrl)
.compression()
.get(`/rooms/${room}`)
.submitRaw();
console.log(
`compressed response: ${compressed.status} encoding-removed ${compressed.headers['content-encoding'] === undefined}`
);
The example confirms that the compression-enabled client returns the room response as a normal status-200 response.
4. Next Chapter¶
Authentication, TLS, and Proxy covers credentials, certificates, and proxy configuration.