6

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
  • 1
    Something tells me you already knew the answer to this! ;)
    – Brad Bell
    Jan 21, 2020 at 19:20

1 Answer 1

9

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.