2

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

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, privacy policy and cookie policy

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