Here’s a complete guide to building and consuming REST APIs using PHP, covering everything from basics to advanced practices. We’ll keep it structured and professional for practical use.
1. Understanding REST API
REST (Representational State Transfer) is an architectural style for building web services. REST APIs allow clients (like web apps, mobile apps) to interact with a server over HTTP using standard methods:
| HTTP Method | Purpose |
|---|---|
| GET | Retrieve resource(s) |
| POST | Create a new resource |
| PUT/PATCH | Update an existing resource |
| DELETE | Remove a resource |
Key Principles:
- Stateless: Each request contains all information to process it.
- Client-server: Separation of client and server concerns.
- Resources: Identified via URIs (e.g.,
/users/1). - Representation: Usually JSON or XML.
2. Setting Up PHP REST API Environment
Requirements:
- PHP 7+ (preferably PHP 8+)
- Web server: Apache, Nginx, or built-in PHP server
- MySQL/MariaDB (or other database)
- Composer (for packages)
Project Structure Example:
/api
index.php
/config
database.php
/controllers
UserController.php
/models
User.php
/routes
api.php
3. Database Connection (PDO)
<?php
// config/database.php
class Database {
private $host = "localhost";
private $db_name = "rest_api";
private $username = "root";
private $password = "";
public $conn;
public function getConnection() {
$this->conn = null;
try {
$this->conn = new PDO(
"mysql:host={$this->host};dbname={$this->db_name}",
$this->username,
$this->password
);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
4. Creating a Model (CRUD Example)
<?php
// models/User.php
class User {
private $conn;
private $table = "users";
public $id;
public $name;
public $email;
public function __construct($db) {
$this->conn = $db;
}
// Read all users
public function read() {
$query = "SELECT id, name, email FROM " . $this->table;
$stmt = $this->conn->prepare($query);
$stmt->execute();
return $stmt;
}
// Create user
public function create() {
$query = "INSERT INTO " . $this->table . " SET name=:name, email=:email";
$stmt = $this->conn->prepare($query);
// sanitize
$this->name = htmlspecialchars(strip_tags($this->name));
$this->email = htmlspecialchars(strip_tags($this->email));
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':email', $this->email);
if($stmt->execute()) return true;
return false;
}
}
5. Creating Controllers
<?php
// controllers/UserController.php
require_once "../models/User.php";
class UserController {
private $db;
private $user;
public function __construct($db) {
$this->db = $db;
$this->user = new User($db);
}
public function getUsers() {
$stmt = $this->user->read();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($users);
}
public function createUser($data) {
$this->user->name = $data['name'] ?? '';
$this->user->email = $data['email'] ?? '';
if($this->user->create()) {
http_response_code(201);
echo json_encode(["message" => "User created"]);
} else {
http_response_code(500);
echo json_encode(["message" => "Failed to create user"]);
}
}
}
6. Routing Requests
<?php
// routes/api.php
require_once "../config/database.php";
require_once "../controllers/UserController.php";
$db = (new Database())->getConnection();
$controller = new UserController($db);
// Get request method
$method = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
// Simple routing
if($uri == '/api/users') {
switch($method) {
case 'GET':
$controller->getUsers();
break;
case 'POST':
$data = json_decode(file_get_contents("php://input"), true);
$controller->createUser($data);
break;
default:
http_response_code(405);
echo json_encode(["message" => "Method not allowed"]);
break;
}
} else {
http_response_code(404);
echo json_encode(["message" => "Not Found"]);
}
7. Consuming REST API with PHP (Client Side)
<?php
$url = "http://localhost/api/users";
// GET Request
$response = file_get_contents($url);
$users = json_decode($response, true);
print_r($users);
// POST Request
$data = ['name' => 'John Doe', 'email' => 'john@example.com'];
$options = [
'http' => [
'header' => "Content-type: application/json\r\n",
'method' => 'POST',
'content' => json_encode($data),
],
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo $result;
8. Best Practices
- Always use JSON for requests and responses.
- Use HTTP status codes properly (200, 201, 400, 404, 500, etc.).
- Validate input data before saving to database.
- Use prepared statements to prevent SQL Injection.
- Enable CORS if API is accessed cross-domain.
- Use authentication (e.g., JWT, OAuth2) for secure APIs.
- Organize project with MVC or similar structure.
- Logging and error handling for production.
9. Optional Enhancements
- Pagination for GET requests
- Filtering and sorting
- Token-based authentication (JWT)
- Rate limiting
- Versioning (
/v1/users)
This gives you a full working REST API with PHP structure, ready for CRUD operations.
Need a Robust, Scalable API for Your Project?
Building a secure and high-performance REST API requires a deep understanding of architectural patterns, security best practices, and database optimization. At NeedleCode, we specialize in:
- Custom PHP API Development: Building lightning-fast APIs with PHP 8 and modern frameworks.
- Secure Authentication Systems: Implementing OAuth2, JWT, and multi-factor authentication.
- Third-Party Integrations: Connecting your applications with payment gateways, social media, and enterprise tools.
Ready to power your web or mobile app with a professional API? Contact NeedleCode Today for a free consultation and let’s build something scalable together.