PHP code example of vanilla / garden-http

1. Go to this page and download the library: Download vanilla/garden-http library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

vanilla / garden-http example snippets


use Garden\Http\HttpClient;

$api = new HttpClient('http://httpbin.org');
$api->setDefaultHeader('Content-Type', 'application/json');

// Get some data from the API.
$response = $api->get('/get'); // requests off of base url
if ($response->isSuccessful()) {
    $data = $response->getBody(); // returns array of json decoded data
}

$response = $api->post('https://httpbin.org/post', ['foo' => 'bar']);
if ($response->isResponseClass('2xx')) {
    // Access the response like an array.
    $posted = $response['json']; // should be ['foo' => 'bar']
}

use Garden\Http\HttpClient;

$api = new HttpClient('https://httpbin.org');
$api->setThrowExceptions(true);

try {
    $api->get('/status/404');
} catch (\Exception $ex) {
    $code = $ex->getCode(); // should be 404
    throw $ex;
}

// If you don't want a specific request to throw.
$response = $api->get("/status/500", [], [], ["throw" => false]);
// But you could throw it yourself.
if (!$response->isSuccessful()) {
    throw $response->asException();
}

try {
    $response = new HttpResponse(501, ["content-type" => "application/json"], '{"message":"Some error occured."}');
    throw $response->asException();
    // Make an exception
} catch (\Garden\Http\HttpResponseException $ex) {
    // Request POST /some/path failed with a response code of 501 and a custom message of "Some error occured."
    $ex->getMessage();
    
    // [
    //      "request" => [
    //          'url' => '/some/path',
    //          'method' => 'POST',
    //      ],
    //      "response" => [
    //          'statusCode' => 501,
    //          'content-type' => 'application/json',
    //          'body' => '{"message":"Some error occured."}',
    //      ]
    // ]
    $ex->getContext();
    
    // It's serializable too.
    json_encode($ex);
}

use Garden\Http\HttpClient;

$api = new HttpClient('https://httpbin.org');
$api->setDefaultOption('auth', ['username', 'password123']);

// This request is made with the default authentication set above.
$r1 = $api->get('/basic-auth/username/password123');

// This request overrides the basic authentication.
$r2 = $api->get('/basic-auth/username/password', [], [], ['auth' => ['username', 'password']]);

use Garden\Http\HttpClient;
use Garden\Http\HttpHandlerInterface

// A custom HTTP client to access the github API.
class GithubClient extends HttpClient {

    // Set default options in your constructor.
    public function __construct(HttpHandlerInterface $handler = null) {
        parent::__construct('https://api.github.com', $handler);
        $this
            ->setDefaultHeader('Content-Type', 'application/json')
            ->setThrowExceptions(true);
    }

    // Use a default header to authorize every request.
    public function setAccessToken($token) {
        $this->setDefaultHeader('Authorization', "Bearer $token");
    }

    // Get the repos for a given user.
    public function getRepos($username = '') {
        if ($username) {
            return $this->get("/users/$username/repos");
        } else {
            return $this->get("/user/repos"); // my repos
        }
    }

    // Create a new repo.
    public function createRepo($name, $description, $private) {
        return $this->post(
            '/user/repos',
            ['name' => $name, 'description' => $description, 'private' => $private]
        );
    }

    // Get a repo.
    public function getRepo($owner, $repo) {
        return $this->get("/repos/$owner/$repo");
    }

    // Edit a repo.
    public function editRepo($owner, $repo, $name, $description = null, $private = null) {
        return $this->patch(
            "/repos/$owner/$repo",
            ['name' => $name, 'description' => $description, 'private' => $private]
        );
    }

    // Different APIs will return different responses on errors.
    // Override this method to handle errors in a way that is appropriate for the API.
    public function handleErrorResponse(HttpResponse $response, $options = []) {
        if ($this->val('throw', $options, $this->throwExceptions)) {
            $body = $response->getBody();
            if (is_array($body)) {
                $message = $this->val('message', $body, $response->getReasonPhrase());
            } else {
                $message = $response->getReasonPhrase();
            }
            throw new \HttpResponseExceptionException($response, $message);
        }
    }
}

function (HttpRequest $request, callable $next): HttpResponse {
    // Do something to the request.
    $request->setHeader('X-Foo', '...');
    
    // Call the next middleware to get the response.
    $response = $next($request);
    
    // Do something to the response.
    $response->setHeader('Cache-Control', 'public, max-age=31536000');
    
    return $response;
}

class HmacMiddleware {
    protected $apiKey;

    protected $secret;

    public function __construct(string $apiKey, string $secret) {
        $this->apiKey = $apiKey;
        $this->secret = $secret;
    }

    public function __invoke(HttpRequest $request, callable $next): HttpResponse {
        $msg = time().$this->apiKey;
        $sig = hash_hmac('sha256', $msg, $this->secret);

        $request->setHeader('Authorization', "$msg.$sig");

        return $next($request);
    }
}

public function send(HttpRequest $request): HttpResponse;

use Garden\Http\HttpClient
use Garden\Http\Mocks\MockHttpHandler;

// Manually apply the handler.
$httpClient = new HttpClient();
$mockHandler = new MockHttpHandler();
$httpClient->setHandler($mockHandler);

// Automatically apply a handler to `HttpClient` instances.
// You can call this again later to retrieve the same handler.
$mockHandler = MockHttpHandler::mock();

// Don't forget this in your phpunit `teardown()`
MockHttpHandler::clearMock();;

// Reset the handler instance
$mockHandler->reset();

use Garden\Http\Mocks\MockHttpHandler;
use Garden\Http\Mocks\MockResponse;

// By default this will return 404 for all requests.
$mockHttp = MockHttpHandler::mock();

$mockHttp
    // Explicit request and response
    ->addMockRequest(
        new \Garden\Http\HttpRequest("GET", "https://domain.com/some/url"),
        new \Garden\Http\HttpResponse(200, ["content-type" => "application/json"], '{"json": "here"}'),
    )
    // Shorthand
    ->addMockRequest(
        "GET https://domain.com/some/url",
        MockResponse::json(["json" => "here"])
    )
    // Even shorter-hand
    // Mocking 200 JSON responses to GET requests is very easy.
    ->addMockRequest(
        "https://domain.com/some/url",
        ["json" => "here"]
    )
    
    // Wildcards
    // Wildcards match with lower priority than explicitly matching requests.
    
    // Explicit wildcard hostname.
    ->addMockRequest("https://*/some/path", MockResponse::success())
    // Implied wildcard hostname.
    ->addMockRequest("/some/path", MockResponse::success())
    // wildcard in path
    ->addMockRequest("https://some-doain.com/some/*", MockResponse::success())
    // Total wildcard
    ->addMockRequest("*", MockResponse::notFound())
;

// Mock multiple requests at once
$mockHttp->mockMulti([
    "GET /some/path" => MockResponse::success()
    "POST /other/path" => MockResponse::json([])
]);

use Garden\Http\Mocks\MockHttpHandler;
use Garden\Http\Mocks\MockResponse;

$mockHttp = MockHttpHandler::mock();

$mockHttp->mockMulti([
    "GET /some/path" => MockResponse::sequence()
        ->push(new \Garden\Http\HttpResponse(500, [], ""))
        ->push(MockResponse::success())
        ->push(MockResponse::json([])
        ->push([]) // Implied json
    ,
]);

use Garden\Http\Mocks\MockHttpHandler;
use Garden\Http\Mocks\MockResponse;
use \Garden\Http\HttpRequest;
use \Garden\Http\HttpResponse;

$mockHttp = MockHttpHandler::mock();
$mockHttp->addMockRequest("*", function (\Garden\Http\HttpRequest $request): HttpResponse {
    return MockResponse::json([
        "requestedUrl" => $request->getUrl(),
    ]);
})

use Garden\Http\Mocks\MockHttpHandler;
use Garden\Http\Mocks\MockResponse;
use Garden\Http\HttpRequest;

$mockHttp = MockHttpHandler::mock();

$mockHttp->addMockRequest("*", MockResponse::success());

// Ensure no requests were made.
$mockHttp->assertNothingSent();

// Check that a request was made
$foundRequest = $mockHttp->assertSent(fn (HttpRequest $request) => $request->getUri()->getPath() === "/some/path");

// Check that a request was not made.
$foundRequest = $mockHttp->assertNotSent(fn (HttpRequest $request) => $request->getUri()->getPath() === "/some/path");

// Clear the history (and mocked requests)
$mockHttp->reset();