April 29, 2025 - 23:04
Creating a RESTful API with PHP Image
PHP

Creating a RESTful API with PHP

Comments

RESTful APIs are a widely used approach for building web services. In this guide, you'll learn the basics of developing a RESTful API using PHP, with practical examples to help you understand the process.

1. RESTful API Basics

REST (Representational State Transfer) is an architectural style that uses HTTP for communication. Each action typically corresponds to an HTTP method:

  • GET – Read data
  • POST – Add new data
  • PUT – Update existing data
  • DELETE – Delete data

2. Building a RESTful API with PHP

2.1. Directory Structure

Use the following structure to organize your API files:

GENEL
/api
    |-- index.php
    |-- config.php
    |-- database.php
    |-- routes.php
    |-- controllers
        |-- UserController.php
    |-- models
        |-- User.php

2.2. Database Setup (Using MySQL)

Create a database and a users table using the SQL below:

SQL
CREATE DATABASE testdb;
USE testdb;

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

2.3. Database Connection (database.php)

PHP
class Database {
    private $host = 'localhost';
    private $db_name = 'testdb';
    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;
    }
}

2.4. User Model (models/User.php)

PHP
class User {
    private $conn;
    private $table_name = 'users';

    public $id;
    public $name;
    public $email;
    public $password;

    public function __construct($db) {
        $this->conn = $db;
    }

    public function read() {
        $query = 'SELECT id, name, email, created_at FROM ' . $this->table_name;
        $stmt = $this->conn->prepare($query);
        $stmt->execute();
        return $stmt;
    }

    public function create() {
        $query = 'INSERT INTO ' . $this->table_name . ' (name, email, password) VALUES (:name, :email, :password)';
        $stmt = $this->conn->prepare($query);

        $stmt->bindParam(':name', $this->name);
        $stmt->bindParam(':email', $this->email);
        $stmt->bindParam(':password', $this->password);

        return $stmt->execute();
    }
}

2.5. User Controller (controllers/UserController.php)

PHP
include_once '../database.php';
include_once '../models/User.php';

$database = new Database();
$db = $database->getConnection();
$user = new User($db);

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $user->read();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($users);
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'));

    $user->name = $data->name;
    $user->email = $data->email;
    $user->password = password_hash($data->password, PASSWORD_DEFAULT);

    if ($user->create()) {
        echo json_encode(['message' => 'User created successfully']);
    } else {
        echo json_encode(['message' => 'Unable to create user']);
    }
}

2.6. Main API File (index.php)

PHP
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type');
include_once 'controllers/UserController.php';

3. Testing the API

Use Postman or cURL to test your API:

List Users:

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

Create User:

SH
curl -X POST http://localhost/api/index.php \
     -H 'Content-Type: application/json' \
     -d '{"name": "John Doe", "email": "john@example.com", "password": "123456"}'

4. API Security Tips

  1. Use HTTPS to encrypt communication.
  2. Authenticate with JWT for secure API access.
  3. Implement rate limiting to protect against abuse.
  4. Sanitize inputs to prevent SQL Injection and XSS attacks.

Related Articles

Comments ()

No comments yet. Be the first to comment!

Leave a Comment