Consuming External APIs (JSON & cURL)
Call other services from PHP — fetch data from a third-party API with cURL, then decode the JSON into PHP data you can use.
What you will learn
- Call an external API with cURL
- Decode JSON responses with json_decode
- Handle the data and errors safely
Talking to the outside world
In the last unit you *served* JSON. Now you will *consume* it. Real apps constantly call other services — a weather API, a currency-rate API, a payment gateway. PHP can make an HTTP request to another server, receive its JSON, and turn it into PHP data. The standard tool for this is cURL, a library built into PHP for making web requests.
*Consuming an API* means your PHP acts like a browser: it sends a request to a URL and reads the response — except the response is JSON data, not an HTML page.
Fetching data with cURL
cURL follows a fixed four-step pattern: open a session, set options (the URL and "return the result to me"), run it, then close it.
<?php
$url = "https://api.exchangerate.host/latest?base=USD";
$ch = curl_init($url); // 1. open
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 2. return result
$response = curl_exec($ch); // 3. run
curl_close($ch); // 4. close
$data = json_decode($response, true); // JSON text -> PHP array
echo "1 USD = " . $data["rates"]["INR"] . " INR";
?>Step by step: curl_init($url) starts a request to the API. curl_setopt(..., CURLOPT_RETURNTRANSFER, true) is the crucial option — it tells cURL to return the response as a string instead of printing it. curl_exec($ch) actually sends the request and gives back the JSON text. After closing, json_decode($response, true) converts that JSON into a PHP associative array, so $data["rates"]["INR"] reads the exchange rate just like any nested array.
Note: Output (in the browser):
1 USD = 83.12 INR
The remote server sent JSON; json_decode turned it into a normal PHP array, and we read a value out of it. From PHP’s point of view, the API response is now just data you can loop, filter or display.
Handling failure
External calls can fail — the service might be down or return an error. Always check before trusting the data, so your page does not crash on a bad response.
<?php
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response === false || $httpCode !== 200) {
echo "Could not reach the service.";
} else {
$data = json_decode($response, true);
// ...use $data...
}
?>curl_getinfo($ch, CURLINFO_HTTP_CODE) reports the status code the remote server sent. We treat the call as failed if curl_exec returned false (a network problem) or the code is not 200 (the server reported an error). Only when both checks pass do we decode and use the data — a small guard that keeps your page calm when the outside world misbehaves.
Note: Output (when the service is down): Could not reach the service. Instead of a fatal crash or a confusing error, the user gets a clear message. This defensive check is the difference between a hobby script and a dependable app.
Tip: For bigger projects, the Guzzle library (installed via Composer) wraps cURL in a far friendlier interface — but cURL is built in and good to understand first, since it is what Guzzle uses underneath.
Q. After fetching JSON from an external API with cURL, how do you turn it into PHP data?
✍️ Practice
- Use cURL to fetch JSON from a free public API and print one field from it.
- Add a status-code check that shows a friendly message if the call fails.
🏠 Homework
- Build a page that calls a public weather or currency API with cURL, decodes the JSON, and displays three values nicely — with error handling.