Building a REST API with PHP and MySQL
Last Updated :
13 Aug, 2024
This brief tutorial is a step-by-step guide on how to develop a REST API using PHP and MySQL. REST API will implement HTTP commands (Get, Post, Put, DELETE) and response will be in form of JSON. For development setup, we will be using the XAMPP while for testing of the API, we will use the Postman app.
Steps to Build REST API with PHP and MySQL
Step 1: Download and Install XAMPP
- Open the XAMPP official website for download.
Xampp Official Website- Download and set up XAMPP; open the XAMPP control panel.
Xampp Control Panel- That completes the installation process of PHP, MySQL, and Apache Server, now start the apache and mysql services.
- Open a browser and navigate to http://localhost/dashboard. You should see the XAMPP dashboard.
Step 2: Create the Database
- To overcome this, you simply have to type the following address in the address bar of your browser http://localhost/phpmyadmin/.
- A new database is created on clicking the “New” button available in the sidebar.
- Type in the new name geeksforgeeks and then click on the “Create” button.
Create geeksforgeeks databaseStep 3: Create a Table
- Select the geeksforgeeks database.
- Click on the "SQL" tab and execute the following SQL code to create a users table
CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
age INT (3) NOT NULL);
Create users tableStep 4: Create the Project Folder
- Navigate to the 'htdocs' directory in your XAMPP installation (usually 'C:\xampp\htdocs').
- Set up a new folder that will be labeled geeksforgeeks_api.
Go to the location and add filesStep 5: Create a Database Connection File
- Navigate to the folder geeksforgeeks_api and in that make a new file called db. php.
- Add the following code to establish a connection to the MySQL database:
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "geeksforgeeks";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
3. Create the API File
- In the root directory of the geeksforgeeks_api, open another file and name it api. php.
- Add the following code to handle various HTTP methods (GET, POST, PUT, DELETE):
PHP
<?php
include 'db.php';
header("Content-Type: application/json");
$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents('php://input'), true);
switch ($method) {
case 'GET':
if (isset($_GET['id'])) {
$id = $_GET['id'];
$result = $conn->query("SELECT * FROM users WHERE id=$id");
$data = $result->fetch_assoc();
echo json_encode($data);
} else {
$result = $conn->query("SELECT * FROM users");
$users = [];
while ($row = $result->fetch_assoc()) {
$users[] = $row;
}
echo json_encode($users);
}
break;
case 'POST':
$name = $input['name'];
$email = $input['email'];
$age = $input['age'];
$conn->query("INSERT INTO users (name, email, age) VALUES ('$name', '$email', $age)");
echo json_encode(["message" => "User added successfully"]);
break;
case 'PUT':
$id = $_GET['id'];
$name = $input['name'];
$email = $input['email'];
$age = $input['age'];
$conn->query("UPDATE users SET name='$name',
email='$email', age=$age WHERE id=$id");
echo json_encode(["message" => "User updated successfully"]);
break;
case 'DELETE':
$id = $_GET['id'];
$conn->query("DELETE FROM users WHERE id=$id");
echo json_encode(["message" => "User deleted successfully"]);
break;
default:
echo json_encode(["message" => "Invalid request method"]);
break;
}
$conn->close();
?>
- After running the installation, it is advised to take the API for a test using the Postman tool.
Steps to Test the API using Postman
1. GET Request:
- Open Postman.
- Specify the request type to Get.
- Enter http://localhost/geeksforgeeks_api/api.php at the end of the request URL.
- Click "Send. "
- Looking at the JSON response, you should be able to get all the users currently in the database.
Screenshots:
GET REQUEST2. POST Request:
- Make the request type to POST instead of GET.
- Enter http://localhost/geeksforgeeks_api/api.php in the request URL.
- The “Body” tab can be selected, and under the “Data format”, choose “Raw” that can be “JSON”.
- Add the following JSON data:
{
"name": "GeeksforGeeks",
"email": "[email protected]",
"age": 28
}
- Click "Send. "
- Post this you should see a success message and the new user should be stored in the database.
POST REQUEST
The data has been added into the darabase- GET Request after POST Request:
GET Request after POST request3. PUT Request:
- Alters the request type to PUT.
- Enter http://localhost/geeksforgeeks_api/api.php?id=1 in the request URL if the user with id=1 is exist.
- In the "Body" tab, add the updated JSON data:
{
"name": "Write for GeeksforGeeks",
"email": "[email protected]",
"age": 26
}
- Click "Send. "
- There should be a success message and after that, the user information will be modified in the database.
PUT request in Postman- GET Request after PUT Request:
4. DELETE Request:
- Modify the request type to delete.
- Enter http://localhost/geeksforgeeks_api/api.php?id=1 of the user with id = 1 added to the request URL (provided there is a user with such ID).
- Click "Send. "
- You should be seeing a success message and in the database, the user will be deleted.
DELETE REQUEST2. GET Request after DELETE Request:
GET REQUEST AFTER DELETEConclusion
But if you follow the measures that are pointed out in this guide, you can create a REST API yourself, using PHP and MySQL. This is the most flexible of the four methods as it gives the developer full control of the APIs and its instantiation to suit the project being developed. This implies that the API is tested with postman to ensure that all the functionalities are responding as required.
Similar Reads
Build a Grocery Store Web App using PHP with MySQL In this article, we are going to build a Grocery Store Web Application using PHP with MySQL. In this application, we can add grocery items by their name, quantity, status (pending, bought, not available), and date. We can view, delete and update those items. There will be a date filtering feature wh
7 min read
Creating a Registration and Login System with PHP and MySQL A registration and login system is a fundamental component of many web applications and provides user authentication and security. This allows users to create an account log in with their login credentials and manage their session securely. By using PHP for server-side scripting and MYSQL for databa
12 min read
Implementing AJAX Live Search with PHP and MySQL AJAX (Asynchronous JavaScript and XML) is a technique used to create dynamic web applications. It allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that web pages can be updated without requiring a full page reload. AJAX Live Search is a
4 min read
How to Build an API With Ruby on Rails? Ruby on Rails API refers to the application programming interface (API) framework provided by the Ruby on Rails (Rails) web application framework. It allows developers to build and expose APIs for their web applications efficiently. Ruby on Rails is a popular web development framework written in the
4 min read
How to Build a RESTful API with Spring Boot and Spring MVC? RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTf
7 min read
Create a Small CRM using PHP and MySQL CRM stands for Customer Relationship Management, which is a strategy for a set of practices, and a technology designed to manage and analyze customer interactions and data throughout the customer lifecycle. Manage contacts by adding, updating, and deleting information such as name, email, phone, and
6 min read