APIs (Application Programming Interfaces) allow PHP applications to fetch data from external services, such as:
β
Weather APIs π¦οΈ
β
Cryptocurrency rates π°
β
User authentication systems π
β
Payment gateways (PayPal, Stripe) π³
In this guide, youβll learn:
β
How to send GET & POST requests using cURL
β
How to fetch JSON responses from APIs
β
How to use Guzzle (a modern alternative to cURL)
β
How to build a mini project that fetches real-world API data
Letβs get started! π
1οΈβ£ What is cURL in PHP?
π‘ cURL (Client URL) is a PHP extension that allows you to send HTTP requests to APIs.
π₯ Why use cURL?
β
Supports GET, POST, PUT, DELETE requests.
β
Works with JSON APIs.
β
Supports authentication (Bearer Token, API Key, OAuth).
2οΈβ£ Making a GET Request with cURL
Letβs fetch random user data from the Random User API.
<?php
$url = "https://randomuser.me/api/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
echo "Random User: " . $data["results"][0]["name"]["first"] . " " . $data["results"][0]["name"]["last"];
?>
π₯ Whatβs happening?
β
curl_init($url)
initializes the request.
β
CURLOPT_RETURNTRANSFER
stores the API response in a variable.
β
json_decode($response, true)
converts JSON into an array.
3οΈβ£ Sending a POST Request with cURL
Letβs send a POST request to a fake API (reqres.in).
<?php
$url = "https://reqres.in/api/users";
$data = ["name" => "Zero Dev", "job" => "PHP Developer"];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
?>
π₯ Whatβs happening?
β
CURLOPT_POST
enables POST requests.
β
CURLOPT_POSTFIELDS
sends JSON data.
β
CURLOPT_HTTPHEADER
sets headers.
4οΈβ£ Fetching API Data with Guzzle (Better Than cURL)
π‘ Guzzle is a modern HTTP client for PHP. Itβs easier to use than cURL!
1οΈβ£ Install Guzzle via Composer
composer require guzzlehttp/guzzle
2οΈβ£ Fetching a GET Request
<?php
require "vendor/autoload.php";
use GuzzleHttp\Client;
$client = new Client();
$response = $client->get("https://randomuser.me/api/");
$data = json_decode($response->getBody(), true);
echo "User: " . $data["results"][0]["name"]["first"] . " " . $data["results"][0]["name"]["last"];
?>
π₯ Why use Guzzle?
β
Cleaner syntax than cURL.
β
Handles timeouts, headers, and JSON easily.
5οΈβ£ Sending a POST Request with Guzzle
<?php
require "vendor/autoload.php";
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post("https://reqres.in/api/users", [
'json' => ["name" => "Zero Dev", "job" => "PHP Developer"]
]);
echo $response->getBody();
?>
π₯ Whatβs happening?
β
post()
method sends JSON data.
β
json
option handles encoding automatically.
6οΈβ£ Handling API Authentication
1οΈβ£ Basic Authentication
<?php
$client = new Client(['auth' => ['username', 'password']]);
$response = $client->get("https://api.example.com/protected");
echo $response->getBody();
?>
2οΈβ£ Bearer Token Authentication
<?php
$client = new Client([
'headers' => ['Authorization' => 'Bearer YOUR_ACCESS_TOKEN']
]);
$response = $client->get("https://api.example.com/protected");
echo $response->getBody();
?>
π₯ Why use authentication?
β
Needed for APIs like GitHub, Stripe, OpenAI, and Twitter.
π― Mini Project: Weather API Fetcher
Letβs build a weather app using the OpenWeather API.
1οΈβ£ Get Your Free API Key
- Sign up at OpenWeather and get an API key.
2οΈβ£ Install Guzzle
composer require guzzlehttp/guzzle
3οΈβ£ Create weather.php
<?php
require "vendor/autoload.php";
use GuzzleHttp\Client;
$apiKey = "YOUR_API_KEY"; // Replace with your OpenWeather API key
$city = "Austin";
$client = new Client();
$response = $client->get("https://api.openweathermap.org/data/2.5/weather", [
'query' => ['q' => $city, 'appid' => $apiKey, 'units' => 'metric']
]);
$data = json_decode($response->getBody(), true);
echo "Weather in " . $data["name"] . ": " . $data["weather"][0]["description"] . ", " . $data["main"]["temp"] . "Β°C";
?>
π₯ Try running it in the browser!
http://localhost/weather.php
π₯ Boom! You just built a weather API fetcher! π
π Final Thoughts
Now you know how to fetch data from APIs like a pro!
β
Use cURL for simple API requests
β
Use Guzzle for advanced API handling
β
Handle authentication securely
β
Build real-world projects with APIs
π Next: Introduction to PHP Frameworks
Happy coding! ππ