I'd like to be able to make HTTP requests from within my plugin to hit an endpoint and get a response. How can I do this?
1 Answer
Craft uses an HTTP library called Guzzle, and it's built-in so you can import and use it from within your plugin. Here's an example:
// imports
use GuzzleHttp;
// GET request
$client = new GuzzleHttp\Client();
$response = $client->request('GET', 'https://example.com', [
'query' => ['exampleParam' => 'example']
]);
$responseBody = json_decode($response->getBody(), true);
// POST request
$client = new GuzzleHttp\Client();
$response = $client->request('POST', 'https://example.com/api', [
'form_params' => [
'example' => 'example',
]
]);
$responseBody = json_decode($response->getBody(), true);
To figure out how to properly format your Guzzle request, refer to the Guzzle Docs.