How to create a simple REST API in PHP
Today, we will learn the most useful full post about How to create a simple REST API in PHP with a token. I will create a user’s CRUD(create, read, update, delete) API with a token in PHP. I’ll show you how to create a simple REST API in PHP with a token from scratch. Most web applications these days are developed applications on the front end and connected to backend APIs written in various languages. In fact, most web applications are day-to-day access and expose data via REST APIs.
In this post, we’ll build a simple demo application, which allows you to create a record, update a record, delete a record and fetch a list of users from the MySQL database via a REST API.
how to create a simple REST API in PHP with a Token
Table Of Concepts
- Table structure for user’s table
- Connection API
- Register API
- Login API
- FetchAll User API
- Update user API
- Delete user API
Table structure for user’s table
CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR(191) NULL DEFAULT NULL ,
`password` VARCHAR(191) NULL DEFAULT NULL ,
`token` VARCHAR(191) NULL DEFAULT NULL ,
`created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY (`id`)
) ENGINE = InnoDB;
Connection API
<?php
//connection.php
header('Content-Type: application/json; charset=utf-8');
$hostname = 'localhost';
$username = 'root';
$userpassword = '';
$databasename = 'devnote';
$conn = mysqli_connect($hostname, $username, $userpassword, $databasename);
/* if(!$conn) {
echo "connection failed";
}
else {
echo "connection succes";
} */
function api_token_check($token) {
global $conn;
$checkuserquery = "SELECT * FROM users WHERE token='$token'";
$resultant = mysqli_query($conn, $checkuserquery);
if(mysqli_num_rows($resultant) > 0) {
return true;
}
return false;
}
?>
Register API
<?php
// register.php
require 'connection.php';
$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod !== 'POST') {
$response['status_code'] = "400";
$response['message'] = "Only POST method is allowed.";
} else {
if(!isset($_POST['username']) || empty($_POST['username'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter Username.";
} else if(!isset($_POST['password']) || empty($_POST['password'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter password.";
} else {
$username = $_POST['username'];
$password = $_POST['password'];
$userQuery = "SELECT * FROM users WHERE username= '$username'";
$resultant_exits = mysqli_query($conn, $userQuery);
if(mysqli_num_rows($resultant_exits) > 0) {
$response['status_code'] = "400";
$response['message'] = $username. " user already exist.";
} else {
$query = "INSERT INTO users (`username`, `password`) VALUES('$username', '$password')";
$resultant = mysqli_query($conn, $query);
if($resultant) {
$response['status_code'] = "200";
$response['message'] = "User successfully added.";
} else {
$response['status_code'] = "400";
$response['message'] = "Something went wrong.";
}
}
}
}
echo json_encode($response);
?>
Login API
<?php
// login.php
require 'connection.php';
$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod !== 'POST') {
$response['user'] = (object)[];
$response['status_code'] = "400";
$response['access_token'] = "";
$response['message'] = "Only POST method is allowed.";
} else {
if(!isset($_POST['username']) || !($_POST['password'])) {
$response['user'] = (object)[];
$response['status_code'] = "400";
$response['access_token'] = "";
$response['message'] = "Please enter username or password.";
} else {
$username = $_POST['username'];
$password = $_POST['password'];
$checkUserquery = "SELECT id, username FROM users WHERE username='$username' and password='$password'";
$resultant = mysqli_query($conn, $checkUserquery);
if(mysqli_num_rows($resultant) > 0) {
while($row = $resultant->fetch_assoc()) {
$id = $row['id'];
$token = bin2hex(random_bytes(16));
$updateToken = mysqli_query($conn, "UPDATE users SET token='$token' WHERE id='$id'");
$response['user'] = $row;
$response['status_code'] = "200";
$response['access_token'] = $token;
$response['message'] = "login success.";
}
} else {
$response['user'] = (object)[];
$response['status_code'] = "400";
$response['access_token'] = "";
$response['message'] = "Please eneter proper credentials.";
}
}
}
echo json_encode($response);
?>
FetchAll User API
<?php
// user-fetch.php
require 'connection.php';
$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod !== 'POST') {
$response['status_code'] = "400";
$response['message'] = "Only POST method is allowed.";
} else {
if(!isset($_POST['token']) || empty($_POST['token'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter Token.";
} else {
if(api_token_check($_POST['token'])) {
$query = "SELECT id, username FROM users";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0) {
while($row = $result->fetch_assoc()){
$response['users'][] = $row;
$response['status_code'] = "200";
}
}
} else {
$response['status_code'] = "400";
$response['message'] = "Token invalid.";
}
}
}
echo json_encode($response);
?>
Update user API
<?php
//user-update.php
require 'connection.php';
$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod !== 'POST') {
$response['status_code'] = "400";
$response['message'] = "Only POST method is allowed.";
} else {
if(!isset($_POST['token']) || empty($_POST['token'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter Token.";
} else {
if(api_token_check($_POST['token'])) {
if(!isset($_POST['id']) || empty($_POST['id'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter id.";
} else if(!isset($_POST['username']) || empty($_POST['username'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter Username.";
} else if(!isset($_POST['password']) || empty($_POST['password'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter password.";
} else {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users set `username` = '$username', `password` = '$password' WHERE id = '$id'";
$result = mysqli_query($conn, $query);
if($result > 0) {
$user = mysqli_query($conn, "SELECT id, username FROM users WHERE id='$id'");
if(mysqli_num_rows($user) > 0 ) {
while($row = $user->fetch_assoc()){
$response["user"]=$row;
}
$response['status_code']="200";
$response['message']="user update success";
} else {
$response["user"] = (object)[];
$response['status_code'] = "400";
$response['message'] = "user update but detail not get";
}
} else {
$response["user"] = (object)[];
$response['status_code'] = "400";
$response['message'] = "user update failed";
}
}
} else {
$response['status_code'] = "400";
$response['message'] = "Token invalid.";
}
}
}
echo json_encode($response);
?>
Delete user API
<?php
//user-delete.php
require 'connection.php';
$requestMethod = $_SERVER["REQUEST_METHOD"];
if ($requestMethod !== 'POST') {
$response['status_code'] = "400";
$response['message'] = "Only POST method is allowed.";
} else {
if(!isset($_POST['token']) || empty($_POST['token'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter Token.";
} else {
if(api_token_check($_POST['token'])) {
if(!isset($_POST['id']) || empty($_POST['id'])) {
$response['status_code'] = "400";
$response['message'] = "Please enter id.";
} else {
$id = $_POST['id'];
$query = "DELETE FROM users WHERE id = '$id'";
$result = mysqli_query($conn, $query);
if($result > 0) {
$response['status_code'] = "200";
$response['message'] = "User has been deleted.";
} else {
$response['status_code'] = "400";
$response['message'] = "User has not been deleted";
}
}
} else {
$response['status_code'] = "400";
$response['message'] = "Token invalid.";
}
}
}
echo json_encode($response);
?>
If you have any questions, please feel free to comment in the comment section. Keep Learning and don’t forget to share this post with your friends.