The HttpRequest
is part of a non-standard extension to PHP, which needs to be installed on your server separately: http://docs.php.net/manual/da/http.install.php
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('http://mywebsite.com/rest/api/','/'),
'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);
// POST
$result = $client->post('people',array('name' => 'Joe'));
$response = $result->process();
$id = $response['id'];
// PUT
$client->put('people/'.$id,array('name' => 'Joe','email' => '[email protected]'));
$client->get('people',array('id' => $id));
$client->delete('people/'.$id);
(source)
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:
<?php
$url = 'https://www.foo.bar/baz.php';
$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.