PHP REST API Tutorial
A REST API allows you to send and receive data from your PHP server using HTTP methods like GET, POST, PUT, DELETE. It is commonly used to build backend services for frontend apps.
REST API एक ऐसी सेवा है जिससे आप PHP सर्वर से डेटा भेज और प्राप्त कर सकते हैं HTTP methods (GET, POST, PUT, DELETE) का उपयोग करके। यह फ्रंटएंड ऐप्स के लिए बैकएंड बनाने में उपयोगी है।
Basic REST API Example
<?php
header("Content-Type: application/json");
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
echo json_encode(["users" => ["Aryan", "Ravi"]]);
break;
case 'POST':
$data = json_decode(file_get_contents("php://input"), true);
echo json_encode(["message" => "User added", "data" => $data]);
break;
case 'PUT':
$data = json_decode(file_get_contents("php://input"), true);
echo json_encode(["message" => "User updated", "data" => $data]);
break;
case 'DELETE':
echo json_encode(["message" => "User deleted"]);
break;
default:
http_response_code(405);
echo json_encode(["error" => "Method not allowed"]);
break;
}
?>
Test Using JavaScript
fetch("/api.php", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "John Doe" })
})
.then(res => res.json())
.then(data => console.log(data));