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;
use Illuminate\Support\Facades\Http;
$response = Http::get('https://api.example.com/data');
$body = $response->body();
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'],
]);
$response = Http::get('https://api.example.com/data', [
'param1' => 'value1',
'param2' => 'value2',
]);
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'],
]);
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'],
]);
$response = Http::post('https://api.example.com/post-json-endpoint', [
'key' => 'value',
'another_key' => 'another_value',
])->header('Content-Type', 'application/json');
Handling Responses:
$response = $client->get('https://api.example.com/data');
$statusCode = $response->getStatusCode();
$headers = $response->getHeaders();
$body = $response->getBody()->getContents();
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();
}
Sending Custom Headers:
$response = $client->get('https://api.example.com/data', [
'headers' => [
'Authorization' => 'Bearer ' . $accessToken,
'Custom-Header' => 'Custom-Value',
],
]);
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();
Laravel HTTP client also supports asynchronous requests:
Timeouts and Options:
$response = Http::timeout(10)->get('https://api.example.com/data');
$responses = Http::pool(function ($pool) {
$pool->get('https://api.example.com/endpoint1');
$pool->get('https://api.example.com/endpoint2');
});
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]);
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
}
}
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.']);
}
}
}
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();
Response status line using client
Top comments (0)