PHP REST API Development

πŸš€ PHP REST API Development – Build a Simple API

REST APIs are the backbone of modern web applications. They allow communication between different systems using HTTP requests like GET, POST, PUT, and DELETE. Let’s build a simple REST API using PHP! πŸ› οΈ


🌍 What is a REST API?

A REST API (Representational State Transfer) is a way for web applications to interact. It follows these principles:

  • Stateless: Each request is independent.
  • Uses HTTP Methods: GET (Read), POST (Create), PUT (Update), DELETE (Remove).
  • Data in JSON Format: APIs exchange data in JSON or XML.

πŸ“Œ Step 1: Create a Simple API Endpoint

βœ… Example: Simple PHP REST API (GET Request)

Let’s create an API that returns a list of users in JSON format.

<?php
header("Content-Type: application/json");

$users = [
    ["id" => 1, "name" => "Alice", "email" => "alice@example.com"],
    ["id" => 2, "name" => "Bob", "email" => "bob@example.com"]
];

echo json_encode($users);
?>

Try It Now

πŸ” Output: JSON response with user data.


πŸ“Œ Step 2: Accepting POST Requests

Now, let’s allow users to send data using a POST request.

βœ… Example: Handling POST Requests

<?php
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $inputData = json_decode(file_get_contents("php://input"), true);
    
    if (isset($inputData["name"]) && isset($inputData["email"])) {
        $response = [
            "message" => "User added successfully!",
            "user" => $inputData
        ];
        echo json_encode($response);
    } else {
        echo json_encode(["error" => "Missing name or email"]);
    }
} else {
    echo json_encode(["error" => "Only POST requests are allowed"]);
}
?>

Try It Now

πŸ” Output: Returns success or error based on the input.


πŸ”„ Step 3: Using PUT & DELETE Requests

REST APIs also support PUT (update) and DELETE (remove) requests. These are often used with ID parameters.

βœ… Example: Handling PUT & DELETE Requests

<?php
header("Content-Type: application/json");

$method = $_SERVER["REQUEST_METHOD"];
$inputData = json_decode(file_get_contents("php://input"), true);

if ($method === "PUT") {
    echo json_encode(["message" => "User updated!", "data" => $inputData]);
} elseif ($method === "DELETE") {
    echo json_encode(["message" => "User deleted!"]);
} else {
    echo json_encode(["error" => "Use PUT or DELETE"]);
}
?>

Try It Now

πŸ” Output: Responds based on the HTTP method used.


🎯 Summary

  • βœ… A REST API follows stateless communication.
  • βœ… PHP can handle GET, POST, PUT, DELETE requests.
  • βœ… APIs return data in JSON format.
  • βœ… Use php://input to read request data.

πŸš€ Next Steps

Now that you know the basics, try integrating your API with a database or using authentication tokens! 🌍