PHP and APIs: Fetching Data with cURL and Guzzle πŸš€

PHP and APIs: Fetching Data with cURL and Guzzle πŸš€

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

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! πŸŽ‰πŸš€

Leave a Reply