Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

list down the use of Guzzle HTTP client in laravel

Making a Simple GET Request
Sending Query Parameters
Sending POST Request with Form Parameters
Handling Responses
how to get ststus code,header,bodycontents using guzzle
Sending Custom Headers
Method is to determine whether a given URL is reachable by making an HTTP request using the Guzzle HTTP client
Http::pool to send multiple end points
How to sends a GET request to GitHub's API with dynamically provided authentication credentials
Creating requests with a client
Response status line using client

Guzzle is an HTTP client that sends HTTP requests to a server and receives HTTP responses. Both requests and responses are referred to as messages.

Guzzle is a popular HTTP client for PHP that makes it easy to send HTTP requests and integrate with web services. Below are some common use cases for Guzzle along with programming examples:

Making a Simple GET Request:
$client->get
$response->getBody()

use GuzzleHttp\Client;

$client = new Client();
$response = $client->get('https://api.example.com/data');
$body = $response->getBody()->getContents();
echo $body;
Enter fullscreen mode Exit fullscreen mode
use Illuminate\Support\Facades\Http;

$response = Http::get('https://api.example.com/data');
$body = $response->body();
Enter fullscreen mode Exit fullscreen mode

Sending Query Parameters:
$client->get
params inside query
another way using Http::get with parameter

$response = $client->get('https://api.example.com/data', [
    'query' => ['param1' => 'value1', 'param2' => 'value2'],
]);
Enter fullscreen mode Exit fullscreen mode
$response = Http::get('https://api.example.com/data', [
    'param1' => 'value1',
    'param2' => 'value2',
]);
Enter fullscreen mode Exit fullscreen mode

Sending POST Request with Form Parameters:
$client->post
form_params for request value

$response = $client->post('https://api.example.com/post-endpoint', [
    'form_params' => ['key' => 'value', 'another_key' => 'another_value'],
]);
Enter fullscreen mode Exit fullscreen mode

Sending JSON Data with POST Request:
$client->post
key and value inside json

$response = $client->post('https://api.example.com/post-json-endpoint', [
    'json' => ['key' => 'value', 'another_key' => 'another_value'],
]);
Enter fullscreen mode Exit fullscreen mode
$response = Http::post('https://api.example.com/post-json-endpoint', [
    'key' => 'value',
    'another_key' => 'another_value',
])->header('Content-Type', 'application/json');
Enter fullscreen mode Exit fullscreen mode

Handling Responses:

$response = $client->get('https://api.example.com/data');
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();
$body = $response->getBody()->getContents();
Enter fullscreen mode Exit fullscreen mode

Handling Exceptions:

use GuzzleHttp\Exception\RequestException;

try {
    $response = $client->get('https://api.example.com/data');
} catch (RequestException $e) {
    // Handle exception, e.g., log error or return false
    echo "Error: " . $e->getMessage();
}
Enter fullscreen mode Exit fullscreen mode

Sending Custom Headers:

$response = $client->get('https://api.example.com/data', [
    'headers' => [
        'Authorization' => 'Bearer ' . $accessToken,
        'Custom-Header' => 'Custom-Value',
    ],
]);
Enter fullscreen mode Exit fullscreen mode

Handling Asynchronous Requests:


$promises = [
    'request1' => $client->getAsync('https://api.example.com/endpoint1'),
    'request2' => $client->getAsync('https://api.example.com/endpoint2'),
];

$results = GuzzleHttp\Promise\settle($promises)->wait();
Enter fullscreen mode Exit fullscreen mode

Laravel HTTP client also supports asynchronous requests:

Timeouts and Options:

$response = Http::timeout(10)->get('https://api.example.com/data');
Enter fullscreen mode Exit fullscreen mode
$responses = Http::pool(function ($pool) {
    $pool->get('https://api.example.com/endpoint1');
    $pool->get('https://api.example.com/endpoint2');
});
Enter fullscreen mode Exit fullscreen mode

Middleware:
Guzzle allows you to add middleware to the request and response lifecycle. Middleware can modify requests and responses.

use GuzzleHttp\HandlerStack;

$stack = HandlerStack::create();
$stack->push(function ($handler) {
    return function ($request, $options) use ($handler) {
        // Modify request or response
        return $handler($request, $options);
    };
});

$client = new Client(['handler' => $stack]);
Enter fullscreen mode Exit fullscreen mode

These examples cover some of the basic use cases of Guzzle. Depending on your requirements, Guzzle provides many more features and options for working with HTTP requests and responses in PHP.

Method is to determine whether a given URL is reachable by making an HTTP request using the Guzzle HTTP client

  protected function checkIfUrlIsWorkingWithGuzzle($url)
    {
        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->get($url, ['http_errors' => false]);

            // Check if the response status code indicates success
            if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
                return true; // Website is reachable
            } else {
                return false; // Website is not reachable
            }
        } catch (\Exception $e) {
            return false; // Error occurred, website is not reachable
        }
    }
Enter fullscreen mode Exit fullscreen mode

How to sends a GET request to GitHub's API with dynamically provided authentication credentials

use GuzzleHttp\Client;
use Illuminate\Http\Request;

class GitHubController extends Controller
{
    public function sendGitHubRequest(Request $request, $username, $password)
    {
        // Create a new instance of the Guzzle HTTP client with the base URI 'https://api.github.com'
        $client = new Client('https://api.github.com');

        // Send a GET request to the '/user' endpoint
        $request = $client->get('/user');

        // Set authentication credentials for the request
        $request->setAuth($username, $password);

        try {
            // Execute the request and get the response
            $response = $client->send($request);

            // Get the response body as a string
            $body = $response->getBody()->getContents();

            // Process the response as needed
            // ...

            return response()->json(['data' => $body]);
        } catch (\Exception $e) {
            // Handle any exceptions that may occur during the request
            return response()->json(['error' => 'Failed to fetch data from GitHub API.']);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating requests with a client

use Guzzle\Http\Client;

$client = new Client('http://baseurl.com/api/v1');

// Create a GET request using Relative to base URL
// URL of the request: http://baseurl.com/api/v1/path?query=123&value=abc)
$request = $client->get('path?query=123&value=abc');
$response = $request->send();

// Create HEAD request using a relative URL with an absolute path
// URL of the request: http://baseurl.com/path?query=123&value=abc
$request = $client->head('/path?query=123&value=abc');
$response = $request->send();

// Create a DELETE request using an absolute URL
$request = $client->delete('http://www.example.com/path?query=123&value=abc');
$response = $request->send();

// Create a PUT request using the contents of a PHP stream as the body
// Specify custom HTTP headers
$request = $client->put('http://www.example.com/upload', array(
    'X-Header' => 'My Header'
), fopen('http://www.test.com/', 'r'));
$response = $request->send();

// Create a POST request and add the POST files manually
$request = $client->post('http://localhost:8983/solr/update')
    ->addPostFiles(array('file' => '/path/to/documents.xml'));
$response = $request->send();

// Check if a resource supports the DELETE method
$supportsDelete = $client->options('/path')->send()->isMethodAllowed('DELETE');
$response = $request->send();
Enter fullscreen mode Exit fullscreen mode

Image description

Response status line using client

Image description

reference
reference

Top comments (0)