PHP REST API: Build Your Own Data

Why Build a REST API?

Ever wondered how apps talk to each other? It’s not through secret handshakes—it’s via REST APIs! Whether you’re building a mobile app, a fancy JavaScript frontend, or an AI-powered robot that needs data, a REST API is the way to go!

Let’s dive in and build a REST API in PHP!

What’s a REST API? (And Why Should We Care?)

A REST API (Representational State Transfer API) allows different applications to communicate over the internet using HTTP requests. It’s like a waiter at a restaurant—

  • You ask for food (a request)
  • The kitchen prepares the food (processes the request)
  • The waiter delivers your food (a response)

Common REST Methods:

  • GET → Retrieve data (e.g., Get all users)
  • POST → Send data (e.g., Create a new user)
  • PUT → Update data (e.g., Update user info)
  • DELETE → Remove data (e.g., Delete a user)

Now, let’s build our own API!

Step 1: Creating a Simple REST API in PHP

Setting Up api.php

First, let’s create a file called api.php and start handling requests.

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

$requestMethod = $_SERVER["REQUEST_METHOD"];

if ($requestMethod === "GET") {
    echo json_encode(["message" => "Hello from the API!", "status" => "success"]);
} else {
    echo json_encode(["error" => "Invalid request method", "status" => "failed"]);
}

Now, if you visit api.php in the browser, you’ll see:

{
    "message": "Hello from the API!",
    "status": "success"
}

Step 2: Handling Different Requests

Let’s improve our API to handle GET, POST, PUT, and DELETE requests.

api.php (Full Version)

header("Content-Type: application/json");
$requestMethod = $_SERVER["REQUEST_METHOD"];
$data = json_decode(file_get_contents("php://input"), true);

switch ($requestMethod) {
    case "GET":
        echo json_encode(["message" => "This is a GET request", "data" => ["id" => 1, "name" => "Alice"]]);
        break;
    
    case "POST":
        echo json_encode(["message" => "Data received!", "data" => $data]);
        break;

    case "PUT":
        echo json_encode(["message" => "Data updated!", "data" => $data]);
        break;

    case "DELETE":
        echo json_encode(["message" => "Data deleted successfully"]);
        break;
    
    default:
        echo json_encode(["error" => "Invalid request method"]);
        break;
}

Now, our API can handle:

  • GET → Fetching data
  • POST → Sending new data
  • PUT → Updating existing data
  • DELETE → Removing data

Step 3: Testing the API (Like a Mad Scientist!)

To test our API, we can use:

  1. Postman → A free tool for making API requests
  2. cURL (Command Line)

Testing with cURL

GET Request:

curl -X GET http://localhost/api.php

POST Request:

curl -X POST -d '{"name":"John Doe"}' -H "Content-Type: application/json" http://localhost/api.php

PUT Request:

curl -X PUT -d '{"name":"Updated User"}' -H "Content-Type: application/json" http://localhost/api.php

DELETE Request:

curl -X DELETE http://localhost/api.php

Step 4: Building a Real-World API (User Management)

Let’s create a User Management API that connects to a database!

Database Setup (users.sql)

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE
);

users.php

$pdo = new PDO("mysql:host=localhost;dbname=mydb", "root", "");
header("Content-Type: application/json");
$requestMethod = $_SERVER["REQUEST_METHOD"];

if ($requestMethod === "GET") {
    $stmt = $pdo->query("SELECT * FROM users");
    echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
}

Now, your API can fetch users from the database

Congrats! You’ve just built a REST API from scratch in PHP! Here’s what you learned:  What a REST API is, How to handle GET, POST, PUT, DELETE, How to connect an API to a database.

Post a Comment

0 Comments