π 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
orXML
.
π 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); ?>
π 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"]); } ?>
π 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"]); } ?>
π 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! π