PHP
    Advanced
    API
    Backend

    Building Your First REST API with PHP

    February 28, 2025
    12 min read

    πŸš€ Introduction

    If you want to build modern backends, mobile apps, dashboards, authentication systems, or connect your website to a database… you must understand REST APIs.

    A REST API allows different software to talk to each other through simple URLs and JSON. And the best part? PHP β€” yes, the same language powering WordPress β€” is still one of the easiest and fastest ways to build an API.

    By the end of this guide, you'll know how to:

    • βœ” Build your first REST API
    • βœ” Return clean JSON responses
    • βœ” Connect to a database
    • βœ” Handle GET, POST, PUT & DELETE
    • βœ” Understand API structure
    • βœ” Avoid beginner mistakes

    Let's begin.


    🧠 What Is a REST API?

    A REST API (Representational State Transfer) is a structured way for clients (web apps, mobile apps, other servers) to request or send data using standard HTTP verbs:

    • GET β†’ retrieve data
    • POST β†’ create data
    • PUT/PATCH β†’ update data
    • DELETE β†’ remove data

    The server responds using JSON, the universal data format.

    Example response:

    {
      "success": true,
      "message": "User created successfully"
    }

    If you can return JSON β†’ you can build APIs.


    🧰 What You Need Before Starting

    • βœ“ PHP 7.4+ (8.0 recommended)
    • βœ“ Apache or Nginx
    • βœ“ MySQL or MariaDB
    • βœ“ Postman or Thunder Client (for testing)
    • βœ“ Basic PHP knowledge

    Folder example:

    /api
       /v1
          index.php
          users.php

    Simple and effective.


    πŸ“¦ Step 1 β€” Create Your API Folder

    Inside your project or localhost:

    mkdir api
    cd api
    mkdir v1

    Inside api/v1, create:

    • index.php
    • users.php

    index.php will act as a router for now.


    πŸ”§ Step 2 β€” Enable JSON Output

    Inside index.php:

    <?php
    header("Content-Type: application/json; charset=UTF-8");
    
    echo json_encode([
        "status" => "online",
        "message" => "API is running!"
    ]);

    Visit:

    http://localhost/api/v1/index.php

    You've just created your first API response.


    πŸ—ƒοΈ Step 3 β€” Connect to the Database

    Create a file db.php:

    <?php
    
    $host = "localhost";
    $user = "root";
    $pass = "";
    $db   = "rest_api";
    
    $conn = new mysqli($host, $user, $pass, $db);
    
    if ($conn->connect_error) {
        die(json_encode([
            "success" => false,
            "error" => $conn->connect_error
        ]));
    }

    Then include it in users.php:

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

    You now have database access.


    πŸ‘€ Step 4 β€” Build Your First GET Endpoint

    Inside users.php:

    if ($_SERVER["REQUEST_METHOD"] === "GET") {
    
        $result = $conn->query("SELECT * FROM users");
    
        $users = [];
        while ($row = $result->fetch_assoc()) {
            $users[] = $row;
        }
    
        echo json_encode([
            "success" => true,
            "data" => $users
        ]);
    }

    Call:

    GET /api/v1/users.php

    Your API returns all users!


    πŸ“ Step 5 β€” Create a POST Endpoint (Add User)

    Add this under the GET block:

    if ($_SERVER["REQUEST_METHOD"] === "POST") {
    
        $data = json_decode(file_get_contents("php://input"), true);
    
        $name  = $conn->real_escape_string($data["name"]);
        $email = $conn->real_escape_string($data["email"]);
    
        $conn->query("INSERT INTO users (name, email) VALUES ('$name', '$email')");
    
        echo json_encode([
            "success" => true,
            "message" => "User created!"
        ]);
    }

    Send POST JSON:

    {
      "name": "John Doe",
      "email": "john@example.com"
    }

    User created.


    πŸ› οΈ Step 6 β€” Add Update (PUT) Endpoint

    if ($_SERVER["REQUEST_METHOD"] === "PUT") {
    
        $data = json_decode(file_get_contents("php://input"), true);
    
        $id    = intval($data["id"]);
        $name  = $conn->real_escape_string($data["name"]);
        $email = $conn->real_escape_string($data["email"]);
    
        $conn->query("UPDATE users SET name='$name', email='$email' WHERE id=$id");
    
        echo json_encode([
            "success" => true,
            "message" => "User updated!"
        ]);
    }

    πŸ—‘οΈ Step 7 β€” Add Delete Endpoint

    if ($_SERVER["REQUEST_METHOD"] === "DELETE") {
    
        $data = json_decode(file_get_contents("php://input"), true);
        $id = intval($data["id"]);
    
        $conn->query("DELETE FROM users WHERE id=$id");
    
        echo json_encode([
            "success" => true,
            "message" => "User deleted!"
        ]);
    }

    CRUD completed.


    πŸ§ͺ Step 8 β€” Test Everything

    Open Postman or Thunder Client:

    GET all users

    GET /api/v1/users.php

    Create a user

    POST /api/v1/users.php

    Body β†’ JSON

    { "name": "Alice", "email": "alice@email.com" }

    Update a user

    PUT /api/v1/users.php
    { "id": 1, "name": "Alice Updated", "email": "alice@updated.com" }

    Delete a user

    DELETE /api/v1/users.php
    { "id": 1 }

    Everything should now work smoothly.


    πŸ›‘οΈ Security Improvements (Real-World Best Practices)

    To upgrade this API to professional level:

    πŸ” 1. Add API Keys

    Block requests without a valid key.

    πŸ›‘ 2. Use Prepared Statements

    Prevent SQL Injection.

    🚧 3. Add Rate Limiting

    Stop brute force and spam.

    🌍 4. Use Routing Libraries

    Slim Framework or Laravel.

    πŸͺͺ 5. Add User Authentication

    JWT or sessions.

    πŸ“¦ 6. Validate All Input

    Never trust user data.


    🧱 Folder Structure (Recommended)

    /api
       /v1
          /controllers
          /models
          index.php
          users.php
       /config
          db.php

    Scalable and clean.


    🌐 Turning Your API Into a Real Product

    Once your REST API is working, you can use it to power:

    • Mobile apps (Flutter, React Native)
    • Web dashboards (React, Vue)
    • Authentication systems
    • Ecommerce
    • SaaS products
    • Internal tools
    • Game backends

    A simple PHP API can grow into a full startup.

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy β€’ Terms of Service