
The modern web relies heavily on Rest APIs to facilitate communication between different applications, enabling everything from user authentication to data exchange between services. While many developers turn to frameworks like Laravel or Symfony to build APIs, it’s entirely possible to create a RESTful API in pure PHP without relying on external libraries or frameworks.
In this article, we’ll explore the process of building a simple CRUD-based REST API using only PHP and MySQL. This tutorial is perfect for those who want to understand the fundamentals of RESTful API development without the complexity of large frameworks.
Follow this video for complete guidance :
Understanding REST APIs
A REST API (Representational State Transfer Application Programming Interface) follows a set of principles that make web services scalable, maintainable, and efficient. RESTful APIs use HTTP methods such as GET, POST, PUT, and DELETE to perform operations on resources, which are usually represented in JSON format.
For our project, we’ll create a User Management API that allows clients to:
- Retrieve a list of users (
GET /users
) - Fetch a single user by ID (
GET /users?id=1
) - Create a new user (
POST /users
) - Update user details (
PUT /users
) - Delete a user (
DELETE /users
)
Project Structure
Before we start coding, let’s outline our project directory structure. This will help keep our code organized and easy to maintain:
php_rest_api/ │── api/ │ ├── users.php │── config/ │ ├── database.php │── .htaccess │── .env (optional) │── README.md
Each file serves a specific purpose:
api/index.php
– Serves as the API entry point and provides a basic overview.api/users.php
– Handles all user-related operations (CRUD).config/database.php
– Establishes a database connection using PDO..htaccess
– Enables clean URLs without.php
extensions.
By following this structure, we ensure our API remains modular and scalable.
Developing Your Own Chat with Stranger System Using PHP
Setting Up the Database
Before coding our API, we need to set up a MySQL database. In this example, we’ll create a database called php_rest_api
with a users
table. The table will have three fields: id
, name
, and email
.
To create the database, use the following SQL command:
CREATE DATABASE rest; USE rest; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL UNIQUE );
Once the database is set up, we can start developing our API.
Building the API
Our API will follow a structured approach using PHP’s built-in functionality. It will:
- Connect to the database using PDO
- Parse incoming HTTP requests
- Handle CRUD operations for user data
- Respond with JSON-formatted data
To ensure security and efficiency, we will:
- Use
PDO
to prevent SQL injection - Structure the API to handle different HTTP methods
- Return proper HTTP status codes for success or failure
config/database.php
<?php class Database{ private $host = 'localhost'; private $db = 'rest'; private $user = 'root'; private $password = ''; public $conn; public function getConnection(){ $this->conn = null; try{ $conn_string = "mysql:host=".$this->host.";dbname=".$this->db; $this->conn = new PDO($conn_string,$this->user,$this->password); } catch(Exception $error){ echo "Connection Error:".$error->getMessage(); } return $this->conn; } }
api/users.php
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json"); require '../config/database.php'; $db = new Database(); $conn = $db->getConnection(); $method = $_SERVER['REQUEST_METHOD']; switch ($method) { case 'GET': if(isset($_GET['id'])){ getUser($_GET['id'],$conn); }else{ getUsers($conn); } break; case 'POST': createUser($conn); break; case 'PUT': updateUser($conn); break; case 'DELETE': deleteUser($conn); break; default: echo json_encode(["message"=>"Invalid request"]); break; } function getUser($id,$conn){ $query = "select * from users where id=:id"; $stmt = $conn->prepare($query); $stmt->bindParam(':id',$id); $stmt->execute(); $user = $stmt->fetch(PDO::FETCH_ASSOC); echo json_encode($user?: ["message"=>"User not found"]); } function getUsers($conn){ $query = "select * from users order by id desc"; $stmt = $conn->prepare($query); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($users); } function createUser($conn){ $data = json_decode(file_get_contents("php://input"),true); if(isset($data['name']) && isset($data['email'])){ $query = "insert into users (name,email) values (:name,:email)"; $stmt = $conn->prepare($query); $stmt->bindParam(':name',$data['name']); $stmt->bindParam(':email',$data['email']); $stmt->execute(); echo json_encode(["message"=>"User Added"]); }else{ echo json_encode(["message"=>"Invalid data"]); } } function updateUser($conn){ $data = json_decode(file_get_contents("php://input"),true); if(isset($data['id']) && isset($data['name']) && isset($data['email'])){ $query = "update users set name=:name, email=:email where id=:id"; $stmt = $conn->prepare($query); $stmt->bindParam(':id',$data['id']); $stmt->bindParam(':name',$data['name']); $stmt->bindParam(':email',$data['email']); $stmt->execute(); echo json_encode(["message"=>"User Updated"]); }else{ echo json_encode(["message"=>"Invalid data"]); } } function deleteUser($conn){ $data = json_decode(file_get_contents("php://input"),true); if(isset($data['id'])){ $query = "delete from users where id=:id"; $stmt = $conn->prepare($query); $stmt->bindParam(':id',$data['id']); $stmt->execute(); echo json_encode(["message"=>"User deleted"]); }else{ echo json_encode(["message"=>"Invalid data"]); } }
Handling API Requests
Our API needs to handle various request types dynamically. Here’s a breakdown of how each HTTP method will function:
- GET – If no ID is provided, return all users. If an ID is passed, fetch a specific user.
- POST – Accept JSON input and create a new user.
- PUT – Accept JSON input to update an existing user.
- DELETE – Accept JSON input to remove a user from the database.
Each request will interact with the database and return a response in JSON format, making it easy for frontend applications to consume.
Enabling Clean URLs with .htaccess
By default, PHP APIs require .php
extensions in URLs (e.g., api/users.php
). However, we can use an .htaccess
file to enable clean URLs like api/users
.
A simple .htaccess
file in the API folder allows us to rewrite URLs:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^api/([a-zA-Z0-9_]+)$ api/$1.php [QSA,L]
This ensures our API endpoints remain clean and user-friendly.
Testing the API with cURL
Once the API is built, we can test it using cURL, a command-line tool for making HTTP requests.
Fetching All Users
curl -X GET http://localhost/php_rest_api/api/users
Fetching a Single User
curl -X GET http://localhost/php_rest_api/api/users?id=1
Creating a New User
curl -X POST http://localhost/php_rest_api/api/users \ -H "Content-Type: application/json" \ -d '{"name": "Lets Try This", "email": "[email protected]"}'
Updating a User
curl -X PUT http://localhost/php_rest_api/api/users \ -H "Content-Type: application/json" \ -d '{"id": 1, "name": "Lets Try This", "email": "[email protected]"}'
Deleting a User
curl -X DELETE http://localhost/php_rest_api/api/users \ -H "Content-Type: application/json" \ -d '{"id": 1}'
Using cURL allows us to quickly verify that our API works as expected.
Best Practices for REST APIs in PHP
When developing APIs, it’s important to follow best practices to ensure security, scalability, and maintainability. Here are some key considerations:
1. Use Proper HTTP Status Codes
Each API response should include an appropriate status code (e.g., 200 OK
, 400 Bad Request
, 500 Internal Server Error
).
2. Implement Authentication
For production APIs, consider using JWT (JSON Web Tokens) or OAuth for user authentication and security.
3. Sanitize User Input
Always validate and sanitize input data to prevent SQL injection and other security threats.
4. Implement Pagination for Large Datasets
If your API returns a large number of records, implement pagination to optimize performance.
5. Log API Requests and Errors
Logging requests and errors helps in debugging and monitoring API usage.
Building a REST API in PHP without a framework is a great way to understand the fundamentals of API development. In this guide, we explored how to:
✅ Set up a database for user management
✅ Handle API requests dynamically
✅ Perform CRUD operations using PHP and MySQL
✅ Format responses in JSON
✅ Enable clean URLs with .htaccess
✅ Test API endpoints using cURL
While this is a basic implementation, it lays the foundation for more advanced features like authentication, rate limiting, and caching.
If you’re looking to take your API to the next level, consider adding JWT authentication, pagination, and request validation. Happy coding! 🚀