PHP Basics · Chapter 21 · JSON & API

PHP JSON & API
Complete Guide in Hindi

PHP JSON और API की पूरी जानकारी — json_encode/decode, cURL से API call करना, REST API बनाना, Authentication, Rate Limiting। Real examples के साथ।

📦 JSON Encode/Decode 🌐 cURL 🏗️ REST API Build 🔑 Authentication 📊 Response Format
JSONData exchange format
cURLHTTP requests PHP से
RESTAPI architecture
BearerToken authentication

📋 इस Article में क्या-क्या है

  1. JSON क्या है?
  2. json_encode() — PHP → JSON
  3. json_decode() — JSON → PHP
  4. JSON Error Handling
  5. cURL — HTTP Requests
  6. GET और POST Requests
  7. REST API बनाना
  8. API Authentication
  9. External APIs Use करना
  10. API Best Practices
1
JSON क्या है?

JSON (JavaScript Object Notation) — lightweight data format जो humans और machines दोनों easily read कर सकते हैं। APIs में data exchange के लिए standard format। PHP ↔ JavaScript ↔ Android ↔ iOS — सब JSON समझते हैं।

JSON FORMAT — STRUCTURE
// JSON — key-value pairs, arrays, nested objects
{
  "id": 1,
  "naam": "Rahul Kumar",
  "umar": 25,
  "active": true,
  "address": {
    "city": "Delhi",
    "pincode": "110001"
  },
  "skills": ["PHP", "MySQL", "Laravel"],
  "deleted_at": null
}
JSON TypePHP EquivalentExample
stringstring"Hello"
numberint / float42, 3.14
booleanbooltrue, false
nullnullnull
object {}array / stdClass{"key": "val"}
array []array[1, 2, 3]

2
json_encode() — PHP → JSON
enc
ode

json_encode()

PHP array/object को JSON string में convert करता है। API response, AJAX reply, data store — सब में ज़रूरी। Flags से output control करो।

PHP 5.2+ Returns: string|false Multiple flags
json_encode() — FLAGS & OPTIONS
<?php
$user = [
  "id" => 1,
  "naam" => "राहुल",
  "email" => "rahul@gmail.com",
  "skills" => ["PHP", "MySQL"],
  "active" => true,
];

// Basic encode
echo json_encode($user);
// {"id":1,"naam":"\u0930\u093e\u0939\u0941\u0932",...}

// JSON_UNESCAPED_UNICODE — Hindi/Unicode as-is
echo json_encode($user, JSON_UNESCAPED_UNICODE);
// {"id":1,"naam":"राहुल",...}

// JSON_PRETTY_PRINT — readable format
echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
// {
// "id": 1,
// "naam": "राहुल",
// }

// JSON_UNESCAPED_SLASHES — URL में backslash नहीं
$url = ["link" => "https://example.com/path"];
echo json_encode($url); // "https:\/\/example.com\/path"
echo json_encode($url, JSON_UNESCAPED_SLASHES); // "https://example.com/path" ✅

// API response helper
function jsonResponse(mixed $data, int $code = 200): never {
  http_response_code($code);
  header("Content-Type: application/json; charset=UTF-8");
  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}
?>

3
json_decode() — JSON → PHP
json_decode() — ASSOCIATIVE ARRAY vs OBJECT
<?php
$json = '{"id":1,"naam":"Rahul","skills":["PHP","MySQL"],"active":true}';

// Default — stdClass object
$obj = json_decode($json);
echo $obj->naam; // Rahul
echo $obj->skills[0]; // PHP
echo $obj->active; // 1 (true)

// true — Associative array (recommended)
$arr = json_decode($json, true);
echo $arr["naam"]; // Rahul
echo $arr["skills"][1]; // MySQL

// Nested JSON decode
$nested = '{"user":{"naam":"Priya","address":{"city":"Mumbai"}}}';
$data = json_decode($nested, true);
echo $data["user"]["address"]["city"]; // Mumbai
?>

4
JSON Error Handling — Safe Decode/Encode
JSON — SAFE HELPERS
<?php
// Safe decode — error handle करो
function safeJsonDecode(string $json): array {
  $data = json_decode($json, true);
  if (json_last_error() !== JSON_ERROR_NONE) {
    throw new InvalidArgumentException(
      "JSON Error: " . json_last_error_msg()
    );
  }
  return $data ?? [];
}

// PHP 8.3+ — json_validate()
if (json_validate($jsonString)) {
  $data = json_decode($jsonString, true);
}

// json_last_error() codes
// JSON_ERROR_NONE — no error
// JSON_ERROR_DEPTH — max stack depth exceeded
// JSON_ERROR_SYNTAX — syntax error
// JSON_ERROR_UTF8 — malformed UTF-8
// JSON_ERROR_CTRL_CHAR — control char error
?>

5
cURL — HTTP Requests भेजना
cURL
http

cURL (Client URL)

PHP से HTTP requests — GET, POST, PUT, DELETE। External APIs call करना, webhooks, payment gateways। Reusable HttpClient class से clean code।

PHP built-in All HTTP methods Headers, Auth support
cURL — BASIC GET REQUEST
<?php
// Basic GET request
function httpGet(string $url, array $headers = []): array {
  $ch = curl_init();
  curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true, // String return करो
    CURLOPT_TIMEOUT => 30, // 30 seconds max
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_SSL_VERIFYPEER => true, // SSL verify करो
    CURLOPT_USERAGENT => "HindiNotesPoint/1.0",
  ]);

  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $error = curl_error($ch);
  curl_close($ch);

  if ($error) {
    throw new RuntimeException("cURL Error: $error");
  }
  return ["code" => $httpCode, "body" => $response];
}

// Usage
$result = httpGet("https://jsonplaceholder.typicode.com/users/1");
$user = json_decode($result["body"], true);
echo $user["name"];
?>

6
Reusable HttpClient Class — GET, POST, PUT, DELETE
HttpClient CLASS — Complete
<?php
class HttpClient {
  private array $defaultHeaders = ["Accept: application/json"];
  private int $timeout = 30;

  public function withToken(string $token): static {
    $this->defaultHeaders[] = "Authorization: Bearer $token";
    return $this;
  }

  public function get(string $url, array $params = []): array {
    if ($params) $url .= "?" . http_build_query($params);
    return $this->request("GET", $url);
  }

  public function post(string $url, array $data = []): array {
    return $this->request("POST", $url, $data);
  }

  public function put(string $url, array $data = []): array {
    return $this->request("PUT", $url, $data);
  }

  public function delete(string $url): array {
    return $this->request("DELETE", $url);
  }

  private function request(string $method, string $url, array $data = []): array {
    $ch = curl_init();
    $headers = $this->defaultHeaders;
    $options = [
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_TIMEOUT => $this->timeout,
      CURLOPT_CUSTOMREQUEST => $method,
      CURLOPT_SSL_VERIFYPEER => true,
    ];
    if ($data) {
      $body = json_encode($data);
      $headers[] = "Content-Type: application/json";
      $headers[] = "Content-Length: " . strlen($body);
      $options[CURLOPT_POSTFIELDS] = $body;
    }
    $options[CURLOPT_HTTPHEADER] = $headers;
    curl_setopt_array($ch, $options);
    $response = curl_exec($ch);
    $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    if ($error) throw new RuntimeException("cURL: $error");
    return [
      "status" => $statusCode,
      "data" => json_decode($response, true) ?? $response,
    ];
  }
}

// Usage — Method chaining
$client = (new HttpClient())->withToken("your-api-token");

// GET
$users = $client->get("https://api.example.com/users", ["page" => 1]);
// POST
$newUser= $client->post("https://api.example.com/users", ["naam" => "Rahul"]);
// DELETE
$del = $client->delete("https://api.example.com/users/42");
?>

7
REST API बनाना — Router + Endpoints
REST API — HTTP methods (GET/POST/PUT/DELETE) को database operations (Read/Create/Update/Delete) से map करना। Proper HTTP status codes return करना।
HTTP MethodEndpointActionStatus
GET/api/usersसब users fetch200
GET/api/users/42एक user fetch200 or 404
POST/api/usersNew user create201
PUT/api/users/42User update200
DELETE/api/users/42User delete204
REST API — api.php (Simple Router)
<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *"); // CORS

$method = $_SERVER["REQUEST_METHOD"];
$uri = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$parts = explode("/", trim($uri, "/"));
// /api/users/42 → ["api", "users", "42"]
$resource = $parts[1] ?? ""; // "users"
$id = isset($parts[2]) ? (int)$parts[2] : null;

// Request body (POST/PUT)
$body = json_decode(file_get_contents("php://input"), true) ?? [];
$pdo = getDB();

// Route — Users resource
if ($resource !== "users") {
  http_response_code(404);
  echo json_encode(["error" => "Resource not found"]);
  exit;
}

match($method) {
  "GET" => function() use ($pdo, $id) {
    if ($id) {
      $stmt = $pdo->prepare("SELECT id, naam, email FROM users WHERE id=?");
      $stmt->execute([$id]);
      $user = $stmt->fetch();
      if (!$user) { http_response_code(404); echo json_encode(["error" => "Not found"]); exit; }
      echo json_encode(["success" => true, "data" => $user]);
    } else {
      $users = $pdo->query("SELECT id, naam, email FROM users LIMIT 50")->fetchAll();
      echo json_encode(["success" => true, "data" => $users, "count" => count($users)]);
    }
  }(),

  "POST" => function() use ($pdo, $body) {
    $stmt = $pdo->prepare("INSERT INTO users (naam, email) VALUES (:naam, :email)");
    $stmt->execute([":naam" => $body["naam"] ?? "", ":email" => $body["email"] ?? ""]);
    http_response_code(201);
    echo json_encode(["success" => true, "id" => $pdo->lastInsertId()]);
  }(),

  "DELETE" => function() use ($pdo, $id) {
    $pdo->prepare("DELETE FROM users WHERE id=?")->execute([$id]);
    http_response_code(204);
  }(),

  default => function() {
    http_response_code(405);
    echo json_encode(["error" => "Method not allowed"]);
  }()
};
?>

8
API Authentication — Bearer Token
API TOKEN — GENERATE & VERIFY
<?php
// Token generate करो (Login endpoint)
function generateApiToken(int $userId): string {
  $token = bin2hex(random_bytes(32)); // Secure random
  $hash = hash("sha256", $token);
  $expires = date("Y-m-d H:i:s", strtotime("+30 days"));

  getDB()->prepare("INSERT INTO api_tokens (user_id, token_hash, expires_at) VALUES (?,?,?)")
         ->execute([$userId, $hash, $expires]);
  return $token; // Plain token return, hash नहीं
}

// Middleware — हर API request पर verify करो
function authenticate(): array {
  $auth = $_SERVER["HTTP_AUTHORIZATION"] ?? "";
  $token = str_replace("Bearer ", "", $auth);
  if (empty($token)) {
    http_response_code(401);
    die(json_encode(["error" => "Unauthorized — Token missing"]));
  }
  $hash = hash("sha256", $token);
  $stmt = getDB()->prepare("SELECT u.* FROM users u JOIN api_tokens t ON t.user_id=u.id WHERE t.token_hash=? AND t.expires_at > NOW()");
  $stmt->execute([$hash]);
  $user = $stmt->fetch();
  if (!$user) {
    http_response_code(401);
    die(json_encode(["error" => "Unauthorized — Invalid token"]));
  }
  return $user;
}

// Protected endpoint में use
$currentUser = authenticate(); // 401 if no valid token
echo json_encode(["profile" => $currentUser]);
?>

9
External APIs — Real Examples
EXTERNAL APIs — Weather, SMS, Payment
<?php
// 1. OpenWeatherMap API
function getWeather(string $city, string $apiKey): array {
  $url = sprintf(
    "https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric",
    urlencode($city), $apiKey
  );
  $result = (new HttpClient())->get($url);
  return [
    "city" => $result["data"]["name"],
    "temperature" => $result["data"]["main"]["temp"],
    "description" => $result["data"]["weather"][0]["description"],
  ];
}
$weather = getWeather("Delhi", "your_api_key");
echo "Delhi: {$weather['temperature']}°C — {$weather['description']}";

// 2. SMS API (Twilio-style)
function sendSMS(string $to, string $message, string $apiKey): bool {
  $result = (new HttpClient())
    ->withToken($apiKey)
    ->post("https://api.smsprovider.com/send", [
      "to" => $to,
      "message" => $message,
    ]);
  return $result["status"] === 200;
}

// 3. Webhook receive करना
// POST /webhook/payment — Payment gateway callback
$payload = file_get_contents("php://input");
$signature = $_SERVER["HTTP_X_SIGNATURE"] ?? "";
$expected = hash_hmac("sha256", $payload, "webhook_secret");
if (!hash_equals($expected, $signature)) {
  http_response_code(401);
  die("Invalid webhook signature");
}
$event = json_decode($payload, true);
// Process payment event...
?>

10
API Best Practices — Standard Response Format
STANDARD API RESPONSE STRUCTURE
<?php
// Consistent response format — always same structure
class ApiResponse {
  public static function success(mixed $data, string $message = "OK", int $code = 200): never {
    http_response_code($code);
    header("Content-Type: application/json");
    echo json_encode([
      "success" => true,
      "message" => $message,
      "data" => $data,
      "timestamp" => time(),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
  }

  public static function error(string $message, int $code = 400, mixed $errors = null): never {
    http_response_code($code);
    header("Content-Type: application/json");
    echo json_encode([
      "success" => false,
      "message" => $message,
      "errors" => $errors,
      "timestamp" => time(),
    ]);
    exit;
  }
}

// Usage in endpoints
ApiResponse::success($users, "Users fetched");
ApiResponse::success($newUser, "User created", 201);
ApiResponse::error("Validation failed", 422, $errors);
ApiResponse::error("Not found", 404);
ApiResponse::error("Server error", 500);
?>
API Pattern: Authenticate → Validate input → Business logic → ApiResponse::success/error। Consistent format + proper HTTP status codes।
HTTP CodeमतलबUse Case
200OKGET, PUT success
201CreatedPOST success (new resource)
204No ContentDELETE success
400Bad RequestInvalid request format
401UnauthorizedToken missing/invalid
403ForbiddenValid token, no permission
404Not FoundResource नहीं मिला
422UnprocessableValidation failed
429Too Many RequestsRate limit exceeded
500Server ErrorUnexpected server error

निष्कर्ष

PHP JSON और API modern web development का core है। REST APIs से frontend, mobile apps, और third-party services सब connect होते हैं।

json_encode() — JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES हमेशा।

json_decode($json, true) — true pass करो — array मिलेगा।

HttpClient class — Reusable, testable। curl_* functions directly avoid करो।

Bearer Token — DB में hash store, plain token response में। Ch.15 same pattern।

Consistent response format — success/data/message/timestamp हमेशा।

Webhook — hash_hmac से signature verify करो — HMAC-SHA256।

🚀 अगला Chapter: Chapter 22: PHP Security — XSS, CSRF, SQL Injection, Password Hashing, Secure Headers। PHP Series का Final Chapter।