This tutorial help to create rest client using Guzzle library, which is a PHP rest client framework to consume rest service. I am creating a Client of the guzzle and access GitHub API. I will let you know how to access the first rest endpoint using the guzzle. You need to download Guzzle github.
The Guzzle has the following features,
- All the power of cURL with a simple interface.
- Powered by the Symfony2 EventDispatcher.
- Includes a custom node.js webserver to test your clients.
- Persistent connections and parallel requests.
- Streams request and response bodies
- Service descriptions for quickly building clients.
- Use all of the code or only specific components.
- Plugins for caching, logging, OAuth, mocks, and more
How to download and configure Guzzle
Step 1: Download the zip file from here.
Step 2: Extract the above zip file and copy all files into xampp/htdocs/guzzle_test
folder.
Step 3: Now run composer update
the command(please make sure your root folder is xampp/htdocs/guzzle_test
), this command will download all dependency plugins into the vendor folder.
Step 4: Created a new test.php
file and put the below code into this file.
<!-- wp:preformatted --> <pre class="wp-block-preformatted">require_once 'vendor/autoload.php'; use GuzzleHttp\Client; $client = new Client([ // Base URI is used with relative requests 'base_uri' => 'https://api.github.com/', // You can set any number of default request options. 'timeout' => 2.0, //ssl false 'verify' => false ]); $response = $client->request('GET'); //$client = new Client('https://api.github.com/'); //$request = $client->get(); //$response = $request->send(); echo "</pre> <!-- /wp:preformatted --> <!-- wp:preformatted --> <pre class="wp-block-preformatted">"; echo $response->getBody(); ?></pre> <!-- /wp:preformatted -->
line #1
use for load all classes from the vendor folder and I am using a PHP 'use'
operator, which will use for giving aliases to names of classes, interfaces or other namespaces.
line #5
created Client instances of guzzle which takes 'base_uri'
: for base url ,’timeout'
: request timeout of request and 'verify'
: is use non SSL verification.
after the rest client creation, I called the request method that will takes the rest endpoint and query as parameters, here I haven’t passed anything so that will access all GitHub rest endpoints.
to print the response, I am using getBody()
method of guzzle.