Skip to content

Instantly share code, notes, and snippets.

@splittingred
Last active April 30, 2019 09:39
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save splittingred/4689218 to your computer and use it in GitHub Desktop.
Example of modRest, a REST Client, in MODX 2.3.
$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' => 'joe@doe.com'));
$client->get('people',array('id' => $id));
$client->delete('people/'.$id);
@PatchRanger
Copy link

Cool, I use it, thank you for nice gist!
One note though: in curlOptions it is better to use CURLOPT_* settings instead of modX aliases as all of those parameters get passed to CURL. It leads to silently failing curl_setopt_array (as it doesn't recognize the option timeout) and the whole CURL request fails with indistinct error message No URL set!.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment