How to Write a REST API in PHP in 30 Minutes: A Step-by-Step Guide for Beginners

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

How to Write a REST API in PHP in 30 Minutes: For Beginners



Creating your own REST API is an important step for any web developer. An API allows your application to communicate with other services, mobile apps, or the frontend. In this article, we will break down how to write a simple but fully functional REST API in pure PHP in just 30 minutes. You will learn how to handle HTTP requests, work with JSON, and connect a database. No frameworks — just pure PHP and clear examples.



What is a REST API and Why Do You Need It?



REST (Representational State Transfer) is an architectural style for creating web services. An API built on REST principles uses standard HTTP methods to work with resources:



  • GET — retrieving data (e.g., a list of users);
  • POST — creating a new resource;
  • PUT — updating an existing resource;
  • DELETE — deleting a resource.


In modern web development, REST APIs are used everywhere: from mobile applications to microservices. By learning how to create one in PHP, you will be able to quickly integrate your projects with any clients.



Step 1: Setting Up the Project Structure



Before writing code, create a simple file structure. For our API, we will only need a few files:



  • index.php — the entry point that will handle all requests;
  • .htaccess — for redirecting all requests to index.php (if using Apache);
  • config.php — database connection settings (optional).


Create the .htaccess file in the project root folder:



RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^(.*)$ index.php [QSA,L]


This code redirects all requests that do not point to existing files to index.php. Now our API will handle any URL, for example /api/users or /api/users/1.



Step 2: Creating a Router and Handling Requests



Open the index.php file and write the basic routing logic. We will determine the HTTP method and URL, and then call the corresponding functions.



<?phpheader("Content-Type: application/json; charset=UTF-8");header("Access-Control-Allow-Origin: *");header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");header("Access-Control-Allow-Headers: Content-Type, Authorization");

$method = $_SERVER['REQUEST_METHOD'];$request = explode('/', trim($_SERVER['PATH_INFO'] ?? '/', '/'));

// Simple routerswitch ($request[0] ?? '') { case 'users': handleUsers($method, $request); break; default: http_response_code(404); echo json_encode(["message" => "Route not found"]); break;}

function handleUsers($method, $request) { $id = $request[1] ?? null; switch ($method) { case 'GET': if ($id) { // Get a single user echo json_encode(["message" => "Get user with id $id"]); } else { // Get all users echo json_encode(["message" => "Get all users"]); } break; case 'POST': $input = json_decode(file_get_contents("php://input"), true); echo json_encode(["message" => "Create user", "data" => $input]); break; case 'PUT': if ($id) { $input = json_decode(file_get_contents("php://input"), true); echo json_encode(["message" => "Update user with id $id", "data" => $input]); } else { http_response_code(400); echo json_encode(["message" => "ID is requ

Blogs

Book Recommendations