Building a REST API in PHP (Step-by-Step, with Best Practices)

Author

Kritim Yantra

Aug 30, 2025

Building a REST API in PHP (Step-by-Step, with Best Practices)

Picture this: you’ve built your first PHP project, uploaded it to your shared hosting account, and you’re so excited to connect it to your shiny new frontend app. But then—💥 error messages everywhere, weird JSON responses, and security warnings you don’t even understand.

Sound familiar? Trust me, we’ve all been there. Building APIs isn’t just about “making it work.” If you don’t follow best practices, you’ll end up with slow APIs, security holes, and endless headaches in production.

The good news? Creating a clean, fast, and secure REST API in PHP is easier than you think—and I’m going to walk you through it step by step.


🧩 What is a REST API (In Plain English)?

Think of a REST API like a waiter in a restaurant.

  • You (the client) ask for food (data).
  • The waiter (API) takes your request to the kitchen (server).
  • The kitchen (database) prepares the dish and hands it back through the waiter.

That’s it! REST APIs are all about sending requests (GET, POST, PUT, DELETE) and receiving consistent responses, usually in JSON format.


️ Step 1: Project Setup

Let’s create a simple REST API using plain PHP (no frameworks).

Directory Structure

project-root/
│── api/
│   ├── index.php
│   ├── db.php
│   └── users.php
└── .htaccess
  • index.php: Main entry point (routes requests).
  • db.php: Database connection.
  • users.php: User-related API endpoints.
  • .htaccess: For pretty URLs (optional if using Apache).

🗄️ Step 2: Database Connection (db.php)

We’ll use PDO for safe, prepared SQL queries.

<?php
// db.php
$host = "localhost";
$db_name = "my_api";
$username = "root";
$password = "";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db_name;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
    die(json_encode(["error" => "Database connection failed."]));
}

Best Practice: Always use PDO with prepared statements to prevent SQL Injection.


📡 Step 3: Routing Requests (index.php)

We’ll read the HTTP method and endpoint.

<?php
// index.php
header("Content-Type: application/json; charset=UTF-8");
require_once "db.php";

$requestMethod = $_SERVER["REQUEST_METHOD"];
$path = explode("/", trim($_SERVER["REQUEST_URI"], "/"));

if ($path[0] === "users") {
    require "users.php";
} else {
    echo json_encode(["error" => "Invalid endpoint"]);
}

👤 Step 4: User Endpoints (users.php)

Let’s implement CRUD operations.

<?php
// users.php

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

elseif ($requestMethod === "POST") {
    $data = json_decode(file_get_contents("php://input"), true);
    if (!isset($data["name"], $data["email"])) {
        echo json_encode(["error" => "Missing fields"]);
        exit;
    }
    $stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    $stmt->execute([$data["name"], $data["email"]]);
    echo json_encode(["success" => true]);
}
  • GET /users → fetch all users.
  • POST /users → create a new user.

🛡️ Step 5: Best Practices (Don’t Skip These!)

  1. Validation is everything

    • Always check if input fields exist and are valid.
    • Example: reject invalid emails before saving.
  2. Use Proper HTTP Status Codes

    http_response_code(201); // Created
    http_response_code(400); // Bad Request
    http_response_code(404); // Not Found
    
  3. Return Consistent JSON Responses
    Clients love consistency—always return JSON, even on errors.

  4. Security First

    • Hide database errors from users.
    • Use HTTPS (SSL).
    • Add authentication (JWT or API keys) for protected routes.
  5. Organize Your Code

    • Keep routes, DB, and business logic in separate files.
    • Makes scaling easier later.

Pro Tip

Think of your REST API as a public coffee machine .
If you don’t add a coin slot (authentication), anyone can walk up, press buttons, and get free coffee (your data). Always secure your endpoints.


✅ Final Thoughts

Building a REST API in PHP doesn’t have to be overwhelming. By following clean coding practices, validating input, and securing endpoints, you’ll save yourself endless late-night debugging sessions.

Quick Recap:

  • Use PDO + prepared statements.
  • Route cleanly.
  • Validate and sanitize input.
  • Return JSON consistently.
  • Secure your API with authentication.

👉 Now, go ahead and try creating a simple /products API following this same structure. It’s the best way to practice!


❓ Beginner-Friendly FAQ

Q1: Can I build a REST API without a framework in PHP?
Yes! Plain PHP works fine for small APIs. For bigger projects, consider Laravel or Slim.

Q2: How do I secure my PHP REST API?
Use HTTPS, authentication (JWT/API keys), and validate all input to prevent SQL injection or XSS.

Q3: Should I always return JSON?
Yes—REST APIs are expected to return JSON consistently, so your frontend apps can parse responses easily.


💬 Your Turn

What’s the biggest struggle you’ve faced when building your first PHP API—security, routing, or debugging?
Drop your thoughts in the comments—I’d love to hear your story!

Tags

Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts

Understanding SOLID Design Principles in Laravel (For Beginners)
Kritim Yantra Kritim Yantra
Feb 24, 2025
Laravel Repository Pattern Explained: Clean Architecture for Developers
Kritim Yantra Kritim Yantra
Mar 09, 2025