PHP JSON & API
Complete Guide in Hindi
PHP JSON और API की पूरी जानकारी — json_encode/decode, cURL से API call करना, REST API बनाना, Authentication, Rate Limiting। Real examples के साथ।
📋 इस Article में क्या-क्या है
- JSON क्या है?
- json_encode() — PHP → JSON
- json_decode() — JSON → PHP
- JSON Error Handling
- cURL — HTTP Requests
- GET और POST Requests
- REST API बनाना
- API Authentication
- External APIs Use करना
- API Best Practices
JSON (JavaScript Object Notation) — lightweight data format जो humans और machines दोनों easily read कर सकते हैं। APIs में data exchange के लिए standard format। PHP ↔ JavaScript ↔ Android ↔ iOS — सब JSON समझते हैं।
{
"id": 1,
"naam": "Rahul Kumar",
"umar": 25,
"active": true,
"address": {
"city": "Delhi",
"pincode": "110001"
},
"skills": ["PHP", "MySQL", "Laravel"],
"deleted_at": null
}
| JSON Type | PHP Equivalent | Example |
|---|---|---|
| string | string | "Hello" |
| number | int / float | 42, 3.14 |
| boolean | bool | true, false |
| null | null | null |
| object {} | array / stdClass | {"key": "val"} |
| array [] | array | [1, 2, 3] |
$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;
}
?>
$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
?>
// 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
?>
// 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"];
?>
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");
?>
| HTTP Method | Endpoint | Action | Status |
|---|---|---|---|
| GET | /api/users | सब users fetch | 200 |
| GET | /api/users/42 | एक user fetch | 200 or 404 |
| POST | /api/users | New user create | 201 |
| PUT | /api/users/42 | User update | 200 |
| DELETE | /api/users/42 | User delete | 204 |
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"]);
}()
};
?>
// 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]);
?>
// 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...
?>
// 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);
?>
| HTTP Code | मतलब | Use Case |
|---|---|---|
| 200 | OK | GET, PUT success |
| 201 | Created | POST success (new resource) |
| 204 | No Content | DELETE success |
| 400 | Bad Request | Invalid request format |
| 401 | Unauthorized | Token missing/invalid |
| 403 | Forbidden | Valid token, no permission |
| 404 | Not Found | Resource नहीं मिला |
| 422 | Unprocessable | Validation failed |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Server Error | Unexpected 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।