Quick start
Six steps from a one-liner to concurrent requests. Each step can be run on its own in the CLI.
1. A request in one line
For a script or a quick check, the Cast facade is enough:
use Flytachi\Winter\Cast\Cast;
$response = Cast::get('https://httpbin.org/get', ['q' => 'winter'])->send();
$response->getStatusCode(); // 200
$response->json()['args']; // ['q' => 'winter']The second argument holds the query parameters. json() returns an array, or null if the
body is not a JSON object.
2. A client configured once
In an application it is more convenient to build a client with a base address and headers:
use Flytachi\Winter\Cast\Client\CastClient;
$api = CastClient::create()
->withBaseUrl('https://httpbin.org')
->withHeader('X-Api-Key', 'demo')
->withUserAgent('my-app/1.0')
->withTimeout(10);
$echo = $api->get('headers')->send()->json();
$echo['headers']['X-Api-Key']; // "demo"
$echo['headers']['User-Agent']; // "my-app/1.0 WinterCast/2.0.0 curl/8.11.0"The path headers is appended to the base address. Your User-Agent comes first; Cast adds
its own version and the cURL version after it.
3. Send JSON
$created = $api->post('post')
->withJsonBody(['title' => 'Hello', 'tags' => ['a', 'b']])
->send()
->json();
$created['json']; // ['title' => 'Hello', 'tags' => ['a', 'b']]withJsonBody() encodes the data and sets Content-Type: application/json.
4. Handle an error
A 4xx/5xx response is an ordinary response. Call throw() to get an exception:
use Flytachi\Winter\Cast\Exception\ClientErrorException;
use Flytachi\Winter\Cast\Exception\NetworkException;
try {
$api->get('status/404')->send()->throw();
} catch (ClientErrorException $e) {
$e->getStatusCode(); // 404
} catch (NetworkException $e) {
// the server is unreachable or a timeout expired
}More in Error handling.
5. Download a file
A large response is better written straight to disk than kept in memory:
$response = $api->get('bytes/5000000')->sinkTo('/tmp/data.bin')->send()->throw();
filesize('/tmp/data.bin'); // 5000000
$response->isSunk(); // trueOnly a successful (2xx) response is written to the file. More in Files.
6. Several requests at once
$responses = $api->sendAll([
'one' => $api->get('delay/1'),
'two' => $api->get('delay/1'),
'three' => $api->get('delay/1'),
]);
// ~1 second, not 3
$responses['two']->getStatusCode(); // 200Responses come back under the same keys. More in Concurrent requests.
Next
- Mental model — what the library is made of and how a request travels.
- Winter integration — the client as a bean.