Making Requests¶
Contents | Previous: Installation and the First Request | Next: Request Bodies
View in another language — C++ · C#/.NET · Java · Kotlin · Node/TypeScript
After reading this chapter
You can choose an HTTP method and path, then shape one request for an external API with queries, headers, and a per-request timeout.
A request builder is created when a method is selected from the client. It accumulates the request shape until a terminator asks for a response. A terminator is the final call that finishes the builder, submits the request, and selects the response form. A path starts with / and follows the base URL.
1. Methods and Paths¶
The HTTP client provides the seven methods GET, POST, PUT, DELETE, PATCH, HEAD, and OPTIONS. GET reads a resource; POST starts work or creates one. C++ spells DELETE as delete_ because of its keyword.
A path that does not start with / ends with ProtocolError before a request is sent. One request keeps its base URL and path separate. Another base URL uses a separate client or a one-shot.
2. Queries, Headers, and a Timeout¶
A query accumulates names and values after URL encoding. A header applies only to that request and overrides a client default header with the same name. A per-request timeout replaces the client's default timeout only for that request.
// The request overrides both a header and its timeout; the admin client has another
// base URL.
const auto status = co_await client.get ("/ops/nodes/game-server-1/status")
.header ("x-trace-id", "tutorial-1")
.timeout (std::chrono::seconds (5))
.async<node_status_t> ();
auto admin = hc::client_t::create ("http://127.0.0.1:5181")
.basic_auth ("ops", "tutorial-admin")
.build ();
const auto weight = co_await admin.post ("/admin/channels/profile/weight")
.query ("value", "2")
.async<weight_response_t> ();
std::cout << "request shaping: status " << status.status << " weight " << weight.body.weight
<< std::endl;
The code uses separate base URLs for the regular and administrative APIs, adds a per-request header, timeout, and query, then reads the status and changed weight from typed responses.
3. Values That Change Per Request¶
Request-specific credentials, trace IDs, queries, and timeouts belong on the request builder. Headers and credentials that apply to every request belong on the client. A timeout is the time boundary for one attempt, and retry applies it to each attempt. Retry and response-status rules are covered in Redirect, Retry, and Cookies and Response Rules.
Next Chapter¶
Request Bodies adds JSON, form, and multipart bodies.