Skip to content

Instantly share code, notes, and snippets.

@diogenesjup
Forked from daveh/1-file_get_contents.php
Created August 30, 2021 19:12
Show Gist options
  • Save diogenesjup/0c233f2a2043446adc2978ef41d3d848 to your computer and use it in GitHub Desktop.
Save diogenesjup/0c233f2a2043446adc2978ef41d3d848 to your computer and use it in GitHub Desktop.
How to call APIs from PHP: file_get_contents, cURL, Guzzle and SDKs (code to accompany https://youtu.be/wMyP-q3nPd4)
<?php
$payload = json_encode([
"title" => "Updated title"
]);
$options = [
"http" => [
"method" => "PATCH",
"header" => "Content-type: application/json; charset=UTF-8\r\n" .
"Accept-language: en",
"content" => $payload
]
];
$context = stream_context_create($options);
$data = file_get_contents("https://jsonplaceholder.typicode.com/albums/1", false,
$context);
var_dump($data);
print_r($http_response_header);
<?php
$payload = json_encode([
"title" => "Updated title"
]);
$headers = [
"Content-type: application/json; charset=UTF-8",
"Accept-language: en"
];
$ch = curl_init();
/*
curl_setopt($ch, CURLOPT_URL, "https://jsonplaceholder.typicode.com/albums/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
*/
curl_setopt_array($ch, [
CURLOPT_URL => "https://jsonplaceholder.typicode.com/albums/1",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => "PATCH",
CURLOPT_POSTFIELDS => $payload,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_HEADER => true
]);
$data = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
var_dump($status_code);
var_dump($data);
<?php
require __DIR__ . "/vendor/autoload.php";
$payload = json_encode([
"title" => "Updated title"
]);
$headers = [
"Content-type" => "application/json; charset=UTF-8"
];
$client = new GuzzleHttp\Client();
$response = $client->patch("https://jsonplaceholder.typicode.com/albums/1", [
"headers" => $headers,
"body" => $payload
]);
var_dump($response->getStatusCode());
var_dump($response->getHeader("Content-type"));
var_dump((string) $response->getBody());
<?php
$api_key = "your api key here";
$data = [
'name' => 'Bob',
'email' => '[email protected]'
];
/*
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => 'https://api.stripe.com/v1/customers',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_USERPWD => $api_key
]);
$data = curl_exec($ch);
curl_close($ch);
var_dump($data);
*/
require __DIR__ . "/vendor/autoload.php";
$stripe = new \Stripe\StripeClient($api_key);
$customer = $stripe->customers->create($data);
echo $customer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment