How to make an HTTP request

How do I make an HTTP request to an external service from a modx snippet?

I found this? does it need including somehow?

Also what is the quickest way to see errors from the php code? I am looking at the error log in the manager dashboard but that is really slow to update

Going with the POST example, I’d create a new snippet called myPostRequest and paste the sample code in it:

 * myPostRequest snippet
$r = new HttpRequest('', HttpRequest::METH_POST);
$r->setOptions(array('cookies' => array('lang' => 'de')));
$r->addPostFields(array('user' => 'mike', 'pass' => 's3c|r3t'));
$r->addPostFile('image', 'profile.jpg', 'image/jpeg');

try {
    $output = $r->send()->getBody();
} catch (HttpException $ex) {
    $output = $ex;

return $ouput

You can then use this on any resource, chunk or template by calling the snippet like this:


How do I include the HttpRequest class

Got error 'PHP message: PHP Fatal error: Class 'HttpRequest' not found in /var/www/vhosts/ on line 5\n'

The HttpRequest is part of a non-standard extension to PHP, which needs to be installed on your server separately:

MODX does ship with a modRest utility that can be used to send requests to an API.

An example of using that could be:

$config = array(
  'baseUrl' => rtrim('','/'),
  'format' => 'json', // json or xml, the format to request 
  'suppressSuffix' => false, // if false, will append .json or .xml to the URI requested
  'username' => 'myuser', // if set, will use cURL auth to authenticate user
  'password' => 'mypass',
  'curlOptions' => array(
    'timeout' => 30, // cURL timeout
    'otherCurlOption' => 1,
  'headers' => array(
    // any HTTP headers to be sent
  'userAgent' => 'MODX RestClient/1.0.0',
  'defaultParameters' => array(
    'api_key' => 'if i want an api key passed always for every request',
    'other_parameter' => 'these are always sent',
$client = new modRest($modx,$config);

$result = $client->post('people',array('name' => 'Joe'));
$response = $result->process();
$id = $response['id'];

// PUT
$client->put('people/'.$id,array('name' => 'Joe','email' => ''));

$client->get('people',array('id' => $id));



That code is fairly heavily geared towards interacting with third party REST APIs, so it really depends on what you want to do.

The simplest PHP code for a GET request is simply file_get_contents, like this:

$url = '';
$result = file_get_contents($url);

That has some restrictions, and doesn’t give you quite the same level of control over the request or response as other options like cURL.

It’s also common in the PHP world to use Guzzle, but you’d need to install that (via Composer) before you can use that as well.

1 Like

FYI, Guzzle 6 is available as an extra:

1 Like