Lightweight PHP RESTful API in Core PHP: A Step-by-Step Guide

Share this post on:

Creating a RESTful API in PHP often involves heavy frameworks like Laravel. However, for projects where a lightweight and framework-free solution is preferred, Core PHP offers a perfect alternative. This article provides a detailed guide on how to build a simple, yet effective, RESTful API using just Core PHP.

Introduction to RESTful APIs in Core PHP

RESTful APIs are essential for enabling communication between different software systems. While frameworks simplify API development, sometimes the overhead of a framework is unnecessary. In such cases, using Core PHP for building a lightweight RESTful API is both practical and efficient.

Why Choose Core PHP for Your RESTful API?

Core PHP offers several advantages when it comes to developing a RESTful API:

  • Minimal Dependencies: Unlike frameworks, Core PHP does not require you to install and manage multiple dependencies.
  • Lightweight and Fast: Core PHP is less resource-intensive, which results in faster execution and response times.
  • Full Control: Using Core PHP gives you complete control over the structure and logic of your API.

Project Setup

Before we dive into the code, let’s set up the project structure.

Here’s the recommended directory structure:


/my-rest-api
    /api
        /v1
            - index.php
    /data
        - users.json
    - .htaccess

Each component serves a specific purpose:

  • api/v1/index.php: The main script handling API requests.
  • data/users.json: A JSON file simulating a database for this example.
  • .htaccess: A file to handle URL rewriting for clean URLs.

Routing with .htaccess

To ensure clean URLs and direct all API requests to our PHP script, use the following .htaccess configuration:


RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/v1/(.*)$ api/v1/index.php?request=$1 [QSANCL]

Core API Logic in PHP

The core logic of our API will be implemented in the api/v1/index.php file. Here’s how you can handle various HTTP requests like GET, POST, PUT, and DELETE.

Handling Requests

First, we need to determine the request method and the specific endpoint requested:


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

$requestMethod = $_SERVER["REQUEST_METHOD"];
$request = $_GET['request'] ?? '';

This snippet reads the HTTP request method (GET, POST, PUT, DELETE) and the request endpoint.

Utility Functions

We will create utility functions to handle user data stored in users.json:


function getUsers() {
    return json_decode(file_get_contents('../../data/users.json'), true);
}

function saveUsers($users) {
    file_put_contents('../../data/users.json', json_encode($users, JSON_PRETTY_PRINT));
}

Implementing CRUD Operations

Now, let’s implement the core CRUD operations:

switch ($requestMethod) {
    case 'GET':
        handleGet($request);
        break;
    case 'POST':
        handlePost();
        break;
    case 'PUT':
        handlePut($request);
        break;
    case 'DELETE':
        handleDelete($request);
        break;
    default:
        http_response_code(405);
        echo json_encode(["message" => "Method Not Allowed"]);
        break;
}

GET Request

To fetch all users or a specific user by ID:


function handleGet($request) {
    $users = getUsers();
    if (empty($request)) {
        echo json_encode($users);
    } else {
        $userId = explode('/', $request)[0];
        $user = array_filter($users, fn($u) => $u['id'] == $userId);
        echo $user ? json_encode(array_values($user)[0]) : json_encode(["message" => "User not found"], 404);
    }
}

POST Request

To add a new user:


function handlePost() {
    $input = json_decode(file_get_contents("php://input"), true);
    $users = getUsers();
    $newUser = ["id" => end($users)['id'] + 1, "name" => $input['name'], "email" => $input['email']];
    $users[] = $newUser;
    saveUsers($users);
    echo json_encode($newUser, 201);
}

PUT Request

To update an existing user:


function handlePut($request) {
    $input = json_decode(file_get_contents("php://input"), true);
    $users = getUsers();
    $userId = explode('/', $request)[0];
    foreach ($users as &$user) {
        if ($user['id'] == $userId) {
            $user['name'] = $input['name'];
            $user['email'] = $input['email'];
            saveUsers($users);
            echo json_encode($user);
            return;
        }
    }
    echo json_encode(["message" => "User not found"], 404);
}

DELETE Request

To delete a user:


function handleDelete($request) {
    $users = getUsers();
    $userId = explode('/', $request)[0];
    foreach ($users as $key => $user) {
        if ($user['id'] == $userId) {
            unset($users[$key]);
            saveUsers($users);
            echo json_encode(["message" => "User deleted"]);
            return;
        }
    }
    echo json_encode(["message" => "User not found"], 404);
}

Testing the API

Once your API is set up, you can test it using tools like Postman or cURL. Below are examples of how to interact with the API:

  • GET All Users: GET http://your-domain.com/api/v1/
  • GET Specific User: GET http://your-domain.com/api/v1/1
  • Create New User: POST http://your-domain.com/api/v1/ with JSON body {"name": "New User", "email": "new@example.com"}
  • Update User: PUT http://your-domain.com/api/v1/1 with JSON body {"name": "Updated User", "email": "updated@example.com"}
  • Delete User: DELETE http://your-domain.com/api/v1/1

Conclusion

Building a RESTful API using Core PHP offers a lightweight and flexible solution ideal for projects where minimizing dependencies is crucial. With this guide, you can easily extend the API to include more features like authentication and database integration as needed.


FAQs about Lightweight PHP RESTful API

1. What is a RESTful API in PHP?

A RESTful API in PHP allows different systems to communicate using standard HTTP methods like GET, POST, PUT, and DELETE. It enables CRUD operations on resources.

2. Why should I use Core PHP for a RESTful API?

Core PHP is lightweight, fast, and does not require additional dependencies, making it an ideal choice for simple APIs where you need full control over the implementation.

3. How do I secure a RESTful API in Core PHP?

You can secure your API by implementing token-based authentication, validating inputs, and using HTTPS to encrypt data transmission.

4. Can I integrate a database with this API?

Yes, you can easily extend this API to interact with a database like MySQL by replacing the JSON file with database queries.

5. Is it possible to add authentication to this API?

Absolutely! You can implement various authentication methods like Basic Auth, OAuth, or JWT (JSON Web Token) to secure your API.

6. What are the best practices for RESTful API development?

Best practices include using appropriate HTTP status codes, ensuring idempotency in methods like PUT and DELETE, and versioning your API to manage changes.