Usage examples for SendGrid php-http-client
// If running this outside of this context, use the following include and
// comment out the two includes below
// require __DIR__ . '/vendor/autoload.php';
include(dirname(__DIR__) . '/lib/Client.php');
// This gets the parent directory, for your current directory use getcwd()
$path_to_config = dirname(__DIR__);
$apiKey = getenv('SENDGRID_API_KEY');
$headers = ['Authorization: Bearer ' . $apiKey];
$client = new SendGrid\Client('https://api.sendgrid.com', $headers, '/v3');
// This will force client to throw exception in case of 4xx or 5xx HTTP Status response
$client->setThrowException(true);
// and you can set your our own error level if required. By default $code == 0 (Exception) is triggered
// $client->setThrowException(true, E_USER_WARNING);
$query_params = ['limit' => 100, 'offset' => 0];
$request_headers = ['X-Mock: 200'];
$response = $client->api_keys()->get(null, $query_params, $request_headers);
echo $response->statusCode();
echo $response->body();
echo $response->headers();
$query_params = ['limit' => 100, 'offset' => 0];
$request_headers = ['X-Mock: 200'];
$retryOnLimit = true;
$response = $client->api_keys()->get(null, $query_params, $request_headers, $retryOnLimit);
echo $response->statusCode();
echo $response->body();
echo $response->headers();
$response = $client->api_keys()->_($api_key_id)->delete();
echo $response->statusCode();
echo $response->body();
echo $response->headers();
$request_body = [
'name' => 'My PHP API Key',
'scopes' => [
'mail.send',
'alerts.create',
'alerts.read'
]
];
$response = $client->api_keys()->post($request_body);
echo $response->statusCode();
echo $response->body();
echo $response->headers();
$response_body = json_decode($response->body());
$api_key_id = $response_body->api_key_id;
$request_body = [
'name' => 'A New Hope',
'scopes' => [
'user.profile.read',
'user.profile.update'
]
];
$response = $client->api_keys()->_($api_key_id)->put($request_body);
echo $response->statusCode();
echo $response->body();
echo $response->headers();
$request_body = [
'name' => 'A New Hope'
];
$response = $client->api_keys()->_($api_key_id)->patch($request_body);
echo $response->statusCode();
echo $response->body();
echo $response->headers();
try {
$response = $client->setThrowException(true)->api_keys()->_($WRONG_api_key)->patch($request_body);
}
catch(ClientException $e) {
var_dump(
$e->getErrors(),
$e->getHttpStatus(),
$e->getShortTrace());
exit;
}