Skip to content

Instantly share code, notes, and snippets.

@zofe
Last active September 28, 2016 16:16
Show Gist options
  • Save zofe/8bcd6a3d6d5832e8256bf6cb45cc0fad to your computer and use it in GitHub Desktop.
Save zofe/8bcd6a3d6d5832e8256bf6cb45cc0fad to your computer and use it in GitHub Desktop.
general purpose rest client
<?php
//general purpose rest client
function rest_helper($url, $params = null, $body="", $verb = "GET", $format = "json", $auth_token='mytoken')
{
$cparams = array(
"http" => array(
"method" => $verb,
"ignore_errors" => true,
"timeout" => 5,
)
);
$cparams["http"]["header"] = '';
//token autorizzazione
if ($auth_token) {
$cparams["http"]["header"] .= "X-Auth-Token: {$auth_token}\r\n";
}
//post parametri
if ($params !== null) {
$params = http_build_query($params);
if (in_array($verb, array("POST", "PUT"))) {
$cparams["http"]["content"] = $params;
$cparams["http"]["header"] .= "Content-type: application/x-www-form-urlencoded\r\n";
$cparams["http"]["header"] .= "Content-Length: ".strlen($params)."\r\n";
} else {
$url .= "?" . $params;
}
//post body
} elseif($body!== null) {
if ($format == "json") {
$cparams["http"]["header"] .= "Content-Type: application/json\r\n";
$cparams["http"]["content"] = json_encode($body, JSON_FORCE_OBJECT);
} else {
$cparams["http"]["content"] = $body;
}
}
//lettura risultati
$context = stream_context_create($cparams);
$res = file_get_contents($url, false, $context);
switch ($format) {
case "json":
$r = json_decode($res);
return $r;
case "xml":
$r = simplexml_load_string($res);
return $r;
}
return $res;
}
$data = ["data"=>
[
"type"=> "customers",
"send_payment_mail"=> 1,
"contact_id"=> 888888,
"company_name"=> "XXX LLC",
"first_name"=> "Judy",
"last_name"=> "OKeefe",
"address"=> "97534 Jody Summit Suite 660Federicoborough, NM 73044",
"address_2"=> "17659 Arlo Prairie\nEast Maggie, AZ 08883-9180",
"address_3"=> "18540 Luther Loop Apt. 581\nZboncakland, MO 55875",
"postal_code"=> "13727-4208",
"city"=> "Lelandshire",
"province"=> "DZ",
"tax_code"=> "Pariatur.",
"vat"=> "Quis qui.",
"email"=> "[email protected]",
"date_of_birth"=> "2009-04-21",
"gender"=> 1,
"phone_number"=> "+1 (601) 507-0285",
"phone_number_2"=> "(294) 732-2247",
]
];
$risposta = rest_helper('xxxx', null, $data, "POST", "json", 'mytoken');
echo json_encode($risposta);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment