14. Working with APIs (PHP)

1️⃣ REST API Basics

🔹 What is an API?

API (Application Programming Interface) allows two applications to communicate with each other.

Example:

  • Your website → sends request → API → returns data

🔹 What is REST API?

REST (Representational State Transfer) is a standard way to build APIs using HTTP methods.

🔹 Common HTTP Methods:

MethodUse
GETFetch data
POSTSend data
PUTUpdate data
DELETEDelete data

🔹 Example API Request:

GET https://api.example.com/users

🔹 Response (JSON):

{
"name": "Aditya",
"email": "test@gmail.com"
}

2️⃣ Fetch API Using PHP (cURL)

cURL is used in PHP to send API requests.


🔹 Simple GET Request:

<?php
$url = "https://jsonplaceholder.typicode.com/posts/1";$ch = curl_init();curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);$response = curl_exec($ch);curl_close($ch);echo $response;
?>

🔹 POST Request Example:

<?php
$url = "https://jsonplaceholder.typicode.com/posts";$data = [
"title" => "My Post",
"body" => "This is content",
"userId" => 1
];$ch = curl_init($url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Content-Type: application/json"
]);$response = curl_exec($ch);curl_close($ch);echo $response;
?>

3️⃣ JSON Handling in PHP

JSON is the most common data format used in APIs.


🔹 Convert PHP Array → JSON

<?php
$data = [
"name" => "Aditya",
"age" => 25
];$json = json_encode($data);echo $json;
?>

🔹 Convert JSON → PHP Array

<?php
$json = '{"name":"Aditya","age":25}';$data = json_decode($json, true);echo $data['name'];
?>

🔹 Convert JSON → Object

<?php
$json = '{"name":"Aditya","age":25}';$data = json_decode($json);echo $data->name;
?>

4️⃣ Real-Life Example (API + JSON)

<?php
$url = "https://jsonplaceholder.typicode.com/users";$response = file_get_contents($url);$users = json_decode($response, true);foreach($users as $user){
echo $user['name'] . "<br>";
}
?>

5️⃣ Important Concepts for Students

  • API = Data source
  • JSON = Data format
  • cURL = Request tool
  • Always handle errors (important in real projects)

6️⃣ Bonus (Best Practice)

if(curl_errno($ch)){
echo "Error: " . curl_error($ch);
}