Core\Http\Client::request
Core\Http\Client::request(
Core\Http\Method $method,
string|Core\Http\Target $url,
{…},
): Core\Http\ResponseSends an HTTP request with a method your program chooses while it runs, and returns the server's answer.
Core\Http\Client has one function for each common method, such as get, post and delete. request takes the method as its first argument, a Core\Http\Method value, so the method can come from a variable. It also sends OPTIONS and TRACE, which have no function of their own. It takes the same options as the other functions and returns the same Core\Http\Response.
request checks two things before it sends. A GET or HEAD request with a body throws a RuntimeError. A POST or PATCH that is retried can make the server do the same thing twice. Such a retry needs retryIdempotencyKey, a key the server uses to see that a request is a repeat. Without it, request throws a RuntimeError.
If a TLS connection fails, the error names the cause and the fix (TLS connections).
Good to know: the examples run without a network, so every request in them throws an error before it is sent. They show an OPTIONS request, the two checks, and a job that sends saved changes.
Parameters
$methodCore\Http\MethodThe HTTP method to send, as aCore\Http\Methodcase. APostor aPatchwith retries but withoutretryIdempotencyKeythrows an error before the first attempt. The methodspostandpatchgive a compile error for the same mistake.$urlstring|Core\Http\TargetWhere the request goes. It is a URL that the program wrote, or aCore\Http\TargetfromCore\Http::allowUrl. AtaintedURL comes from outside the program, such as from a request. It is not allowed here. Check it withCore\Http::allowUrlfirst.
Options
deadlineCore\Time\DurationoptionalThe time limit for the whole call. It covers the connection, every redirect, every retry and every wait between retries. If it is not given, the runtime's[http.client] deadlineis used. There is no way to write a call with no deadline.connectTimeoutCore\Time\DurationoptionalHow long the connection alone may take. This time is part ofdeadline, and is not added to it.headersarray<secret string>optionalExtra request headers, by name. Asecretvalue is a value the program must keep hidden, such as an API key. It is allowed here, because a credential must reach the API it is for. Ataintedvalue is not allowed. The runtime adds its own headers as well.followRedirectsuintoptionalHow many redirects to follow. If it is not given, the runtime's[http.client] max_redirectsis used, and its default is0. Each redirect is checked against the outbound policy again, and its address is approved again.retryAttemptsuintoptionalThe total number of attempts, including the first. The default is1, which means no retry.0throws an error. All attempts share one deadline, andretryBackoffsets the wait between them.retryBackoffCore\Time\DurationoptionalThe base delay between retries. The delay doubles after each retry. Each wait is a random time up to that delay, which is called full jitter. If it is not given, it is100ms.retryIdempotencyKeystringoptionalSent as theIdempotency-Keyheader, with the same value on every attempt. It is required forpostandpatchwhenretryAttemptsis given. Every other method also accepts it.jsonmixedoptionalThe value to send asapplication/json. It is encoded once for the whole call. Asecretinside it is sent, as it is in a header. Anullvalue sends the JSON documentnull, not an empty body.formarray<secret tainted string>optionalThe fields to send asapplication/x-www-form-urlencoded, by name.bodysecret tainted string|secret tainted bytes|Core\Http\PartoptionalThe bytes to send exactly as given, with the media type incontentType. Only one ofjson,form,bodyandmultipartmay be given. A call that gives two of them does not compile. A call togetorheadthat gives one of them does not compile either.contentTypestringoptionalThe media type ofbody. It has no effect withoutbody, so giving it alone is a compile error.multipartarray<secret tainted string|Core\Http\Part>optionalThe parts to send asmultipart/form-data, by name.identityCore\Http\IdentityoptionalThe client certificate to send when the server asks for one. Create it withCore\Http\Identity::read. Nothing is sent to a server that does not ask. Two different identities never share a pooled connection. A call without an identity does not share one with a call that has one.tlsCastringoptionalThe PEM certificates to trust for this call. They replace[tls.client] rootscertificates. The URL's host must be in theanchorsgrant ofcapabilities.tls. If it is not, the call throws an error before it connects.tlsPinstring|array<string>optionalOnesha256//<base64>public-key pin, or several. The server is accepted if the hash of its SubjectPublicKeyInfo matches one of them. No certificate chain is checked. Use this to reach a server with a self-signed certificate. The host must be in thepingrant.tlsVerifyHostbooloptionalIf it isfalse, the chain is still checked, and only the name check is skipped. The host must be in theany_namegrant.tlsVerifybooloptionalIf it isfalse, neither the chain nor the name is checked. The handshake signature is still checked, so the server has the key it sent. But nothing shows whose key it is. The host must be in theinsecuregrant.tlsMinVersionstringoptionalThe lowest TLS version this call allows,"1.2"or"1.3". It needs no grant, because it can only make the call stricter. A value below the runtime's[tls.client] min_versionthrows an error.connectTostringoptionalThe IP address to connect to. The URL's host is not looked up, but the certificate is still checked against that host. The host must be in thenet.connect_togrant. The deployment's address policy checks this address like a looked-up one. With aCore\Http\Targetas the URL, this option throws an error, because the target already has its approved addresses.redirectToHttpbooloptionalIf it istrue, a redirect fromhttpsto plainhttpmay be followed. The redirect's host must also be in thenet.downgradegrant. If it is not given, such a redirect throws an error. So a server cannot turn off a call's TLS with oneLocationheader. This option does not affect a plainhttpURL that you request directly.
Return value
Returns Core\Http\Response. A Core\Http\Response with the status, the headers and the body of the reply. A 404 or a 500 is a normal reply and is returned here. Only a request that gets no reply at all throws an error. An https URL is fetched over TLS. The certificate is checked against the certificate authorities in [tls.client] roots.
Errors
RuntimeErrorThe URL is not allowed. It is not a URL, its scheme is nothttporhttps, or it has no host. Ornet.connectdoes not grant the host. Or the host resolves to a loopback, private, link-local or unspecified address thatnet.internaldoes not list. An option is out of range. Adeadline,connectTimeoutorretryBackoffis not a positive duration. OrretryAttemptsis zero. A header name or value contains a control byte, which would end the line early. Anhttpsserver sent a certificate that does not verify against[tls.client] roots, or againsttlsCawhen it is given. Or the certificate is not valid for that name. For these two cases, the message says which setting fixes it. Or the reply is not HTTP, or it is larger than the limit for one request. Before the first attempt, this method checks two mistakes that the other methods find at compile time. A body option on aGetor aHeadthrows an error. Retries on aPostor aPatchwithoutretryIdempotencyKeyalso throw an error.TimeoutErrorThedeadlinepassed before the reply arrived. It covers the connection, every redirect, every retry and every wait between retries. If a wait would end after the deadline, the error is thrown at once, without waiting.IOErrorThe last attempt could not connect to the approved address. Or the connection failed while the request was sent or the reply was read.
Changelog
| Version | Change |
|---|---|
0.0.6 | A failed TLS connection names its cause, who can fix it and how, as TLS connection errors explains. For an expired certificate, the message gives the date it expired and the time on this host's clock. For a wrong pin, it gives the sha256// hash of the server's public key. |
Examples
The examples below run with this configuration file.
# The program may connect to public hosts only.# `internal = []` allows no address on this computer or on a private network.[capabilities.net]internal = []Asking which methods a url allows
<?nvs// Shows how to send an `OPTIONS` request. It asks a server which methods a URL allows.
// There is no `options` function, so `request` sends this method. It is the first argument.// 10.0.0.7 is a private address, so the call throws a `RuntimeError` before it sends anything.try { Core\Http\Response $response = Core\Http\Client::request(Core\Http\Method::Options, 'http://10.0.0.7/orders'); echo 'allowed: ', $response->header('allow') ?? 'unknown', "\n";} catch (RuntimeError $refused) { echo $refused->message, "\n";}Core\Http\Client::request cannot connect to 10.0.0.7: it is private (10/8, 172.16/12, 192.168/16), which `net.internal` does not excepthelp: add `internal = ["10.0.0.7"]` under `[capabilities.net]` in nvs.tomlTwo checks before sending
<?nvs// Shows the two checks `Core\Http\Client::request` makes before it sends anything.
// A `GET` request has no body. So a `GET` request with `json` throws a `RuntimeError`.try { var $search = Core\Http\Client::request(Core\Http\Method::Get, 'https://203.0.113.10/search', { json: ['term' => 'shoes'] });} catch (RuntimeError $noBody) { echo $noBody->message, "\n";}
// A `POST` request that is sent again can create a second order. So a `POST` with// `retryAttempts` also needs `retryIdempotencyKey`. Without it, the call throws a `RuntimeError`.try { var $order = Core\Http\Client::request(Core\Http\Method::Post, 'https://203.0.113.10/orders', { json: ['item' => 'shoes'], retryAttempts: 3 });} catch (RuntimeError $noKey) { echo $noKey->message, "\n";}Core\Http\Client::request: a `GET` sends no body, and `json` is one — put the value in the URL's query, or send it under a verb that carries a bodyCore\Http\Client::request: a repeated `POST` is a second effect rather than a second question, so retrying one needs `retryIdempotencyKey` in the same bag, sent as `Idempotency-Key` and identical across attemptsSending saved changes to a partner
<?nvs// Shows a job that sends saved changes to a partner's server. Each change has its// own method, so the job uses `Core\Http\Client::request` for all of them.
// The key is the path of the change, and the value is its method.array<Core\Http\Method> $changes = [ '/customers/7' => Core\Http\Method::Put, '/orders' => Core\Http\Method::Post, '/carts/3' => Core\Http\Method::Delete,];
uint $sent = 0;uint $kept = 0;foreach ($changes as string $path => Core\Http\Method $method) { try { // Each change is tried up to 3 times. `retryIdempotencyKey` tells the partner // that a repeated request is the same change, so it is done only once. Core\Http\Response $response = Core\Http\Client::request($method, 'http://10.0.0.5' . $path, { deadline: 10s, retryAttempts: 3, retryIdempotencyKey: 'change' . $path }); echo 'sent: ', $path, ' (', $response->status(), ')', "\n"; $sent = $sent + 1; } catch (RuntimeError $error) { // The change stays saved, and the next run of the job tries it again. echo 'kept: ', $path, "\n"; $kept = $kept + 1; }}
// The partner's address is private, so this prints `sent: 0, kept: 3`.echo 'sent: ', $sent, ', kept: ', $kept, "\n";kept: /customers/7kept: /orderskept: /carts/3sent: 0, kept: 3