Usage
Simple requests
A simple request is a request created by the call
method. It's an easy way to perform HTTP requests only by defining the method and URI.
call(string $method, string $uri): HttpClientResponse
Look at the following code to perform a GET request to JSON Placeholder API.
$response = $client->call('GET', 'https://jsonplaceholder.typicode.com/todos/1');
$response->getStatusCode(); // 200
$response->parseJson(); // array
When you use the parseJson
method you're gonna get a response like the following:
[
"userId" => 1,
"id" => 1,
"title" => "delectus aut autem",
"completed" => false
]
This way to perform requests is restricted to using only method and URI, you cannot define headers, body, or other data. To create more flexible requests use prepared requests.
Prepared requests
A prepared request is a flexible way to perform a request. Look at the following code to prepare a POST request with a JSON body.
$client->prepareRequest('POST', 'https://jsonplaceholder.typicode.com/posts');
$client->getRequest()
->setHeader('Content-type', 'application/json')
->setJson(['title' => 'foo', 'body' => 'bar', 'userId' => 1]);
Instead of the above, we can take advantage of method chaining and perform a request in a more functional way.
$client
->prepareRequest('POST', 'https://jsonplaceholder.typicode.com/posts')
->setHeader('Content-type', 'application/json')
->setJson(['title' => 'foo', 'body' => 'bar', 'userId' => 1]);
Finally, you can execute the prepared request with the execute
method.
$response = $client->execute();
$response->getStatusCode(); // 200
$response->parseJson(); // array
After using the parseJson
method you're gonna get a response like the following:
[
'id' => 101,
'title' => 'foo',
'body' => 'bar',
'userId' => 1
]
The request
method is defined in the same way as the call
method with the difference that does not execute the request to the service until the execute
method is called.
To get in deep with all available data you can define in a request take a look at Requests.