Lightweight PHP RESTful API in Core PHP showing laptop with programming code and API development

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

Share this post on:

Most PHP tutorials push you toward Laravel or Symfony the moment you want to make a REST API in PHP. That is fine for large projects, but for a small service, a prototype or a mobile app backend, a framework can be more weight than you need.

In this guide you will create a simple REST API using basic PHP, with no framework and no Composer packages. You will build the four REST API methods (GET, POST, PUT and DELETE), protect them with token authentication, test everything with cURL and Postman, and then learn how to consume the API as a REST web service from another PHP application.

Introduction to RESTful APIs in Core PHP

RESTful APIs let different software systems talk to each other over HTTP. A mobile app, a website or another server sends a request to a URL, and the API answers with data, usually JSON. Each URL represents a resource (for example, a user), and the HTTP method says what to do with it.

Frameworks make this easier, but they also add dependencies, configuration and overhead. When you only need a handful of endpoints, using Core PHP to build a lightweight RESTful API is practical and efficient.

Why Choose Core PHP for Your RESTful API?

  • Minimal dependencies: Nothing to install or keep updated apart from PHP itself.
  • Lightweight and fast: Less code runs per request, so responses are quick and hosting needs are small.
  • Full control: You decide the structure, the routing and the response format.
  • Easy to learn from: Writing it by hand shows you exactly how REST, HTTP status codes and headers work, which carries over to any framework later.

Project Setup

Here is the directory structure we will use:

/my-rest-api
    /api
        /v1
            - index.php
    /data
        - users.json
    - .htaccess
  • api/v1/index.php: The single script that handles every API request.
  • data/users.json: A JSON file that acts as a simple database for this example.
  • .htaccess: Rewrites clean URLs to our script and passes the Authorization header to PHP.

Create data/users.json with a couple of sample users:

[
    { "id": 1, "name": "Asha Patel", "email": "asha@example.com" },
    { "id": 2, "name": "Ravi Shah", "email": "ravi@example.com" }
]

Routing with .htaccess

This configuration sends every request under /api/v1/ to our PHP script. The first rule is needed for token authentication: Apache often strips the Authorization header before PHP can read it, and this line passes it through.

RewriteEngine On

# Pass the Authorization header to PHP (needed for token authentication)
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

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

Note the flags [QSA,L]: QSA keeps any query string and L stops processing further rules.

Core API Logic: Helpers and Token Authentication

All of the logic lives in api/v1/index.php. We start with a JSON response helper, the token check and two functions that read and write our JSON “database”.

A JSON Response Helper

Sending the right HTTP status code matters in a REST API. This small helper sets the status, prints JSON and stops the script, so we never forget either step:

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

function sendJson($data, int $status = 200): void {
    http_response_code($status);
    echo json_encode($data);
    exit;
}

Add Token Authentication to Your PHP REST API

A REST API with no authentication lets anyone read or change your data. The simplest fix in basic PHP is a bearer token: the client sends a secret token in the Authorization header, and the API rejects any request without a valid one.

First, generate a long random token once and keep it out of your code:

php -r "echo bin2hex(random_bytes(32));"

Store it in an environment variable named API_TOKEN (for example with SetEnv API_TOKEN "your-token" in your Apache virtual host). Then add this check:

function requireToken(): void {
    $header   = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    $expected = getenv('API_TOKEN') ?: '';

    if ($expected === ''
        || !preg_match('/^Bearer\s+(.+)$/i', $header, $m)
        || !hash_equals($expected, $m[1])) {
        header('WWW-Authenticate: Bearer');
        sendJson(["message" => "Unauthorized"], 401);
    }
}

Three details are worth noting. hash_equals() compares strings in constant time, which avoids timing attacks. An empty expected token always fails, so a missing environment variable can never leave the API open. And a 401 response with the WWW-Authenticate header tells clients exactly what went wrong.

This is the simplest form of token authentication. For per-user tokens, expiry or revocation, store tokens in a database table or move to JWT (JSON Web Tokens).

Utility Functions

These two functions read and write the users file:

function getUsers(): array {
    $file = __DIR__ . '/../../data/users.json';
    return json_decode(file_get_contents($file), true) ?? [];
}

function saveUsers(array $users): void {
    $file = __DIR__ . '/../../data/users.json';
    file_put_contents($file, json_encode(array_values($users), JSON_PRETTY_PRINT), LOCK_EX);
}

REST API Methods in PHP: GET, POST, PUT and DELETE

The REST API methods map to CRUD operations on a resource:

HTTP methodActionExample endpoint
GETRead one or all usersGET /api/v1/ or GET /api/v1/1
POSTCreate a userPOST /api/v1/
PUTUpdate a userPUT /api/v1/1
DELETEDelete a userDELETE /api/v1/1

GET Request

Return all users, or one user by ID. A missing user returns 404:

function handleGet(string $request): void {
    $users = getUsers();

    if ($request === '') {
        sendJson($users);
    }

    $userId = (int) explode('/', $request)[0];
    foreach ($users as $user) {
        if ((int) $user['id'] === $userId) {
            sendJson($user);
        }
    }
    sendJson(["message" => "User not found"], 404);
}

POST Request

Create a new user. We validate the input and return 201 (Created):

function handlePost(): void {
    $input = json_decode(file_get_contents("php://input"), true);

    if (empty($input['name']) || empty($input['email'])) {
        sendJson(["message" => "name and email are required"], 400);
    }

    $users   = getUsers();
    $newId   = $users ? max(array_column($users, 'id')) + 1 : 1;
    $newUser = ["id" => $newId, "name" => $input['name'], "email" => $input['email']];

    $users[] = $newUser;
    saveUsers($users);
    sendJson($newUser, 201);
}

PUT Request

Update an existing user:

function handlePut(string $request): void {
    $input = json_decode(file_get_contents("php://input"), true);

    if (empty($input['name']) || empty($input['email'])) {
        sendJson(["message" => "name and email are required"], 400);
    }

    $users  = getUsers();
    $userId = (int) explode('/', $request)[0];

    foreach ($users as $i => $user) {
        if ((int) $user['id'] === $userId) {
            $users[$i]['name']  = $input['name'];
            $users[$i]['email'] = $input['email'];
            saveUsers($users);
            sendJson($users[$i]);
        }
    }
    sendJson(["message" => "User not found"], 404);
}

DELETE Request

Delete a user:

function handleDelete(string $request): void {
    $users  = getUsers();
    $userId = (int) explode('/', $request)[0];

    foreach ($users as $i => $user) {
        if ((int) $user['id'] === $userId) {
            unset($users[$i]);
            saveUsers($users);
            sendJson(["message" => "User deleted"]);
        }
    }
    sendJson(["message" => "User not found"], 404);
}

Routing the Request

Finally, authenticate the request, read the HTTP method and call the right handler. Put this at the bottom of index.php:

requireToken();

$requestMethod = $_SERVER['REQUEST_METHOD'];
$request       = trim($_GET['request'] ?? '', '/');

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

Testing the API

Test with Postman or cURL. Replace YOUR_TOKEN with the token you generated. First, confirm that a request without a token is rejected:

curl -i http://your-domain.com/api/v1/
# HTTP/1.1 401 Unauthorized

Then try each method with the token:

  • Get all users: curl -H "Authorization: Bearer YOUR_TOKEN" http://your-domain.com/api/v1/
  • Get one user: curl -H "Authorization: Bearer YOUR_TOKEN" http://your-domain.com/api/v1/1
  • Create a user: curl -X POST -H "Authorization: Bearer YOUR_TOKEN" -H "Content-Type: application/json" -d '{"name":"New User","email":"new@example.com"}' http://your-domain.com/api/v1/
  • Update a user: curl -X PUT -H "Authorization: Bearer YOUR_TOKEN" -H "Content-Type: application/json" -d '{"name":"Updated User","email":"updated@example.com"}' http://your-domain.com/api/v1/1
  • Delete a user: curl -X DELETE -H "Authorization: Bearer YOUR_TOKEN" http://your-domain.com/api/v1/1

In Postman, set the Authorization tab to “Bearer Token” and paste your token once for the whole collection.

How to Consume a REST Web Service in PHP with cURL

Building the API is half the job. Any other PHP application, such as a website, a cron script or another backend, can consume it as a REST web service. cURL ships with PHP and works the same way for any REST API:

$ch = curl_init('https://your-domain.com/api/v1/1');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_HTTPHEADER     => [
        'Accept: application/json',
        'Authorization: Bearer YOUR_TOKEN',
    ],
]);

$body   = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$user = ($status === 200) ? json_decode($body, true) : null;

To send data with POST, add these options before curl_exec():

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    'name'  => 'New User',
    'email' => 'new@example.com',
]));
// also add 'Content-Type: application/json' to CURLOPT_HTTPHEADER

Two habits make consuming a REST web service reliable. Always check the HTTP status code before you decode the body, and always set a timeout so a slow service cannot hang your page. For a quick GET with no headers, file_get_contents() also works, but cURL gives you far more control.

Best Practices and Next Steps

  • Use HTTPS so the token and data are encrypted in transit. A bearer token over plain HTTP can be stolen.
  • Validate every input and return clear 400-level errors, as the POST and PUT handlers above do.
  • Replace the JSON file with MySQL for real projects, using PDO with prepared statements.
  • Version your API (/api/v1/) so you can change it later without breaking existing clients.
  • Use proper status codes: 200 for success, 201 for created, 400 for bad input, 401 for missing or wrong token, 404 for not found and 405 for unsupported methods.
  • Rotate your token if it is ever exposed, and never commit it to Git.

Conclusion

You have now created a simple REST API using basic PHP: four REST API methods, token authentication, correct status codes and a working example of how to consume it as a REST web service. It stays lightweight because it uses nothing but Core PHP. From here, swap the JSON file for a database, add per-user tokens or JWT, and add more resources as your project grows.

FAQs about Creating a REST API in PHP

1. How do I create a simple API in PHP?

A. Create an index.php that reads $_SERVER['REQUEST_METHOD'], routes on the URL, and returns json_encode() output with a JSON content-type header and the right status code. The steps above show a complete working version.

2. What is a RESTful API in PHP?

A. A RESTful API in PHP lets different systems communicate using standard HTTP methods such as GET, POST, PUT and DELETE. It performs CRUD operations on resources and usually returns JSON.

3. Which REST API methods can I use in PHP?

A. GET reads a resource, POST creates one, PUT updates one and DELETE removes one. Return 405 (Method Not Allowed) for any method your API does not support.

4. Why should I use Core PHP for a REST API?

A. Core PHP is lightweight, fast and needs no extra dependencies, which makes it a good fit for simple APIs where you want full control over the implementation.

5. How do I add token authentication to a basic PHP API?

A. Read the bearer token from the Authorization header, compare it with your stored secret using hash_equals(), and return 401 if it does not match. See the token authentication section above for the full code.

6. How do I secure a REST API in Core PHP?

A. Use token-based authentication, serve everything over HTTPS, validate all input and use prepared statements if you connect a database.

7. Can I use other authentication methods besides a simple token?

A. Yes. You can use Basic Auth, OAuth 2.0 or JWT (JSON Web Tokens). A static bearer token is the simplest option, while JWT or database-backed tokens suit multi-user APIs.

8. How do I consume a REST API in PHP?

A. Use cURL (or file_get_contents() for very simple GET requests). Send the token in an Authorization: Bearer header, set a timeout, check the HTTP status code and then decode the JSON response.

9. Can I integrate a database with this API?

A. Yes. Replace the JSON file functions with MySQL queries using PDO and prepared statements. The routing and handler structure stays the same.

10. What are the best practices for REST API development?

A. Use correct HTTP status codes, keep PUT and DELETE idempotent, version your API, validate inputs, use HTTPS and keep secrets out of your source code.

Avatar photo

Piyush Solanki

PHP Tech Lead & Backend Architect

10+ years experience
UK market specialist
Global brands & SMEs
Full-stack expertise

Core Technologies

PHP 95%
MySQL 90%
WordPress 92%
AWS 88%
  • Backend: PHP, MySQL, CodeIgniter, Laravel
  • CMS: WordPress customization & plugin development
  • APIs: RESTful design, microservices architecture
  • Frontend: React, TypeScript, modern admin panels
  • Cloud: AWS S3, Linux deployments
  • Integrations: Stripe, SMS/OTP gateways
  • Finance: Secure payment systems & compliance
  • Hospitality: Booking & reservation systems
  • Retail: E-commerce platforms & inventory
  • Consulting: Custom business solutions
  • Food Services: Delivery & ordering systems
  • Modernizing legacy systems for scalability
  • Building secure, high-performance products
  • Mobile-first API development
  • Agile collaboration with cross-functional teams
  • Focus on operational efficiency & innovation

Piyush Solanki is a seasoned PHP Tech Lead with 10+ years of experience architecting and delivering scalable web and mobile backend solutions for global brands and fast-growing SMEs.

He specializes in PHP, MySQL, CodeIgniter, WordPress, and custom API development, helping businesses modernize legacy systems and launch secure, high-performance digital products.

He collaborates closely with mobile teams building Android & iOS apps, developing RESTful APIs, cloud integrations, and secure payment systems. With extensive experience in the UK market and across multiple sectors, Piyush Solanki is passionate about helping SMEs scale technology teams and accelerate innovation through backend excellence.

    Reach Out Us


    Your name

    Your email

    Subject

    Your message