REST (Representational State Transfer) is an architectural style for web services that uses standard HTTP methods (GET, POST, PUT, DELETE, etc.) to operate on resources via URIs. Medium This tutorial demonstrates how to build a simple REST API in pure PHP (no frameworks) supporting the four main methods: GET, POST, PUT, DELETE.
Why is this useful for beginners? Because it shows the core mechanics of REST in the simplest form: handling requests, sending JSON responses, and processing input. Once you understand the basics here, you can scale it up (with databases, authentication, frameworks, etc.).
1. GET Method
The GET method is typically used to read or retrieve resources.
Code example
Here’s how the tutorial shows it:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$data = array(
array('id' => '1', 'name' => 'Bandung'),
array('id' => '2', 'name' => 'Jakarta'),
array('id' => '3', 'name' => 'Surabaya'),
);
// optional search query parameter
if (!empty($_GET['search'])) {
$key = array_search($_GET['search'], array_column($data, 'name'), true);
$id = $data[$key]['id'];
$name = $data[$key]['name'];
$result = array('id' => $id, 'name' => $name, 'status' => 'success');
} else {
foreach ($data as $d) {
$result['city'][] = array('id' => $d['id'], 'name' => $d['name']);
}
$result['status'][] = 'success';
}
http_response_code(200);
echo json_encode($result);
?>
Explanation & tips
- The headers at the top set CORS (Access‐Control‐Allow‐Origin: *) so any origin can call this API, set response content type to JSON, and restrict allowed HTTP method to GET.
- $data is a hard-coded array representing cities. In a real app this would come from a database.
- The script checks if $_GET[‘search’] is provided: if yes, it searches the name field in the data and returns only the matching city. If not, it returns the full list.
- Response sent with http_response_code(200) and echo json_encode($result);
- For beginners: you should sanitize and validate input when moving to real data sources (databases).
2. POST Method
POST is used to create new resources.
Code example
From the tutorial:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$data = array(
array('id' => '1', 'name' => 'Bandung'),
array('id' => '2', 'name' => 'Jakarta'),
array('id' => '3', 'name' => 'Surabaya'),
);
if (!empty($_POST['name']) && !empty($_POST['id'])) { // new data input
$newdata = array('id' => $_POST['id'], 'name' => $_POST['name']);
$data[] = $newdata;
foreach ($data as $d) {
$result['city'][] = array('id' => $d['id'], 'name' => $d['name']);
}
$result['status'] = 'success';
} else {
foreach ($data as $d) {
$result['city'][] = array('id' => $d['id'], 'name' => $d['name']);
}
$result['status'] = 'success';
}
http_response_code(200);
echo json_encode($result);
?>
Explanation & tips
- Headers allow POST method specifically.
- Again using $data as initial set.
- Checks for $_POST[‘id’] and $_POST[‘name’]. If present, it appends a new item to the $data array. Then returns the full list including the new one.
- In a real application you’d insert into a database. You’d also check for duplicates, enforce data types, return appropriate errors (e.g., 400 Bad Request if missing fields).
- For testing you can use a tool like Postman (as the article mentions) to send a POST request with form-data or JSON.
3. PUT Method
PUT is used to update an existing resource.
Code example
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: PUT");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$data = array(
array('id' => '1', 'name' => 'Bandung'),
array('id' => '2', 'name' => 'Jakarta'),
array('id' => '3', 'name' => 'Surabaya'),
);
$method = $_SERVER['REQUEST_METHOD'];
if ('PUT' === $method) {
parse_str(file_get_contents('php://input'), $_PUT);
}
if (!empty($_PUT['id']) && !empty($_PUT['name'])) {
foreach ($data as &$value) {
if ($value['id'] === $_PUT['id']) {
$value['name'] = $_PUT['name'];
break;
}
}
foreach ($data as $d) {
$result['city'][] = array('id' => $d['id'], 'name' => $d['name']);
}
$result['status'] = 'success';
} else {
foreach ($data as $d) {
$result['city'][] = array('id' => $d['id'], 'name' => $d['name']);
}
$result['status'] = 'success';
}
http_response_code(200);
echo json_encode($result);
?>
Explanation & tips
- Uses Access-Control-Allow-Methods: PUT which signals the API is willing to accept PUT requests.
- Because PHP doesn’t automatically populate $_PUT, the code uses parse_str(file_get_contents(‘php://input’), $_PUT) to convert the raw request body into an array.
- It locates the entry in $data matching the id from $_PUT, and updates the name.
- Then returns the full updated list with status success.
- In real apps: use the right HTTP status codes (e.g., 404 if resource not found, 400 if bad input). Also validate that id exists before updating.
- In restful design: PUT is often idempotent (calling it multiple times with same data yields same effect).
4. DELETE Method
DELETE is used to delete resources.
Code example
<?php
header("Access-Control-Allow‐Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow‐Methods: DELETE");
header("Access-Control-Allow‐Headers: Content‐Type, Access‐Control-Allow‐Headers, Authorization, X-Requested-With");
$data = array(
array('id' => '1', 'name' => 'Bandung'),
array('id' => '2', 'name' => 'Jakarta'),
array('id' => '3', 'name' => 'Surabaya'),
);
$method = $_SERVER['REQUEST_METHOD'];
if ('DELETE' === $method) {
parse_str(file_get_contents('php://input'), $_DELETE);
}
if (!empty($_DELETE['id'])) {
foreach ($data as $d) {
if ($d['id'] != $_DELETE['id']) {
$result['city'][] = array('id' => $d['id'], 'name' => $d['name']);
}
}
$result['status'] = 'success';
} else {
foreach ($data as $d) {
$result['city'][] = array('id' => $d['id'], 'name' => $d['name']);
}
$result['status'] = 'success';
}
http_response_code(200);
echo json_encode($result);
?>
Explanation & tips
- Sets header to allow DELETE method.
- Uses file_get_contents(‘php://input’) + parse_str() to read the body (since $_DELETE isn’t built‐in).
- Checks for id to delete; then filters out the matching item from $data.
- Returns the updated list of cities.
- In real apps: you’d check whether the id exists, then delete in the database, respond with 204 No Content or 200 OK and maybe send minimal body. Also handle errors (404, 403, etc.).
5. Conclusion
The tutorial ends by summarizing that the four methods (GET, POST, PUT, DELETE) cover the core CRUD (Create, Read, Update, Delete) operations via REST API in PHP.
Why it’s a good starting point
- Shows the fundamental mechanics of REST with PHP without the “magic” of a framework.
- Provides simple, readable code examples that you can adapt.
- Helps you understand how HTTP methods correlate to CRUD operations and how to handle different request method types in PHP.
What you should do next
- Replace the static $data array with actual database queries (MySQL, PostgreSQL, etc.).
- Use prepared statements to prevent SQL injection.
- Use proper HTTP status codes for errors and success responses (e.g., 201 Created, 204 No Content for DELETE, 400 Bad Request, 404 Not Found).
- Add request validation (is the id valid? is the name present?).
- Consider authentication/authorization (e.g., API keys, JWT tokens) so only authorized users can change data.
- Accept JSON input (via json_decode(file_get_contents(‘php://input’), true)) instead of form data for POST/PUT/DELETE.
- Structure your code to separate routing, controller logic, and database logic (even if still in plain PHP).
- Add documentation (OpenAPI/Swagger) so clients can understand and test your API.
Final Thoughts
If you’re a beginner PHP developer aiming to build RESTful APIs, this tutorial is an excellent first step. It strips away complexity and shows you how the pieces fit together. Once you’re comfortable with this, you can scale up to frameworks (e.g., Laravel with api.php routes, controllers, resources) or micro-frameworks (e.g., Lumen, Slim), but the core ideas remain the same.
I highly recommend downloading the example files (the author provides a GitHub link) and experimenting: add new endpoints, swap in database logic, handle JSON body input, etc. As you evolve the tutorial code, you’ll build confidence to design real APIs for production.