How to call an external API from PHP
cURL, an authentication header and a decoded JSON response — the three parts of calling any external API from a PHP script.
Almost every external API — payment providers, shipping carriers, CRMs, mapping services — is called from PHP the same way underneath: an HTTP request built with cURL, an authentication credential attached as a header, and a JSON response decoded back into a PHP array once it arrives. The specifics of any one API's endpoints and payloads differ, but this shape barely changes between them.
A basic GET request
<?php
$ch = curl_init('https://api.example.com/v1/status');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
CURLOPT_RETURNTRANSFER is easy to forget and produces confusing results when it is missing — without it, cURL prints the response directly rather than handing it back to your script as a string, so $response ends up empty even though the request itself succeeded. CURLOPT_TIMEOUT matters just as much: without one, a slow or unresponsive API can leave your script — and the PHP worker handling the request — hanging far longer than any reasonable request should take.
Sending authentication
Most APIs expect a credential in a header rather than the URL itself. The exact scheme varies by provider, but a bearer token is the most common pattern:
<?php
$apiKey = getenv('API_KEY');
$ch = curl_init('https://api.example.com/v1/orders');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Accept: application/json',
]);
$response = curl_exec($ch);
curl_close($ch);
Read the credential from an environment variable, as above, rather than typing it directly into a PHP file. See setting environment variables for how to do that without root access, and securing a PHP application for why keeping secrets out of the codebase matters beyond just this one case.
Sending a POST request with a JSON body
<?php
$payload = json_encode([
'customer' => 'Jane Smith',
'amount' => 4999,
]);
$ch = curl_init('https://api.example.com/v1/orders');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 200 && $httpCode < 300) {
$data = json_decode($response, true);
} else {
error_log("API request failed with status $httpCode: $response");
}
Checking for failure properly
curl_exec() returning a value does not mean the request succeeded — it means cURL got a response at all, which could just as easily be an error page from the API as the data you asked for. Always check the HTTP status code, and check for a cURL-level failure separately, since a network problem or timeout produces no HTTP response to check a status code on in the first place:
<?php
if (curl_errno($ch)) {
error_log('cURL error: ' . curl_error($ch));
}
Handling rate limits and retries
Most APIs enforce a request rate limit and signal it with a specific status code, commonly 429, sometimes alongside a header telling you how long to wait. A script calling an API repeatedly — processing a batch of records, for instance — should check for that status and back off rather than hammering the endpoint and having every subsequent call rejected too. A short, capped retry with an increasing delay between attempts handles most transient failures without needing anything more elaborate:
<?php
for ($attempt = 1; $attempt <= 3; $attempt++) {
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode < 500) {
break;
}
sleep($attempt * 2);
}
A higher-level alternative: Guzzle
Raw cURL is worth knowing because it works with nothing beyond PHP itself, but on a project that already uses Composer, a library such as Guzzle handles a lot of the repetitive setup above automatically — timeouts, JSON encoding and decoding, and exceptions instead of manual status-code checks:
composer require guzzlehttp/guzzle
<?php
$client = new \GuzzleHttp\Client(['timeout' => 10]);
$response = $client->post('https://api.example.com/v1/orders', [
'headers' => ['Authorization' => 'Bearer ' . $apiKey],
'json' => ['customer' => 'Jane Smith', 'amount' => 4999],
]);
$data = json_decode($response->getBody(), true);
Either approach reaches the same result. cURL needs nothing installed and is worth understanding regardless, since it is what most higher-level libraries use internally; Guzzle is worth adopting once a project is calling more than one or two endpoints, simply because it removes the boilerplate of repeating the same option-setting on every request. See using Composer on shared hosting if you have not installed a package this way before.
Where this fits with slow-running jobs
A script that calls an API many times in a loop — importing records one at a time rather than in a batch, say — can run for long enough to hit PHP's execution time limit. If the job is inherently long-running rather than something a visitor is waiting on, it belongs in a scheduled script run over cron rather than a browser request stretched to cover it.
Related reading
Node needs a long-running process that shared hosting cannot give it — here is what that means and where a Node app actually belongs.
How to secure a PHP applicationThe handful of defences that stop almost every real attack on a PHP application, and the reasoning behind each one.
How to set environment variables on your hostingWithout root access, environment variables come from a control panel screen where one exists, or from a .env file your app loads itself.
How to check which PHP version your site usesA one-line PHP script and the PHP settings screen in your control panel both show the exact version your site runs on.