• Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
PHP Lift
  • Home
  • Demos
  • Advertisement
PHP Lift
  • Home
  • PHP
  • MySQL
  • Demos
  • HTML
  • CSS
  • jQuery
  • Framework
  • Social
  • Request Tutorial
  • Follow
    • Facebook
    • Twitter
    • Google+
    • Pinterest
    • Youtube
    • Instagram
    • RSS
Simple PHP REST API with Slim, PHP & MySQL
Home
MySQL

Simple PHP REST API with Slim, PHP & MySQL

March 3rd, 2022 Huzoor Bux API, MySQL, PHP 2 comments

Facebook Twitter Google+ LinkedIn Pinterest

A REST API is a type of API that makes it easier for developers to build and maintain APIs. These APIs are often used to create web applications, but they can also be used for mobile apps, desktop apps, and other software programs.

REST stands for Representational State Transfer. The “REST” in the acronym is just a way of saying that the API uses HTTP methods like GET or POST as verbs to represent different kinds of actions. For example, if you wanted to create a new account with an online store using the REST API, you would use the POST method to do so.

PHP is an open-source scripting language and framework primarily used to create web pages. It is one of the most popular programming languages in the world, ranking second with about 13% of all developers use it, compared to Java’s 8%.

See Also: Working with APIs in PHP

PHP API is an extension that provides PHP scripts with the ability to read and write data from sources outside of the script. This allows for third-party systems to integrate into a script without having any additional programming knowledge.

DEMO
DOWNLOAD CODE

HTTP methods:

GET: Used to retrieve and search for data.

POST: Used to insert data.

PUT: Used to update data.

DELETE: Used to delete data.

Add below .htaccess file in your API folder http://localhost/api

RewriteEngine On

RewriteBase /api # if hosting api files on root use only /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php [QSA,L]

Database design and table:
database name => phpgang
table name => restAPI
column names => id, name, email, IP, date
db.sql
Database file runs in your MySQL to create a database and add data in the table.

-- 
-- Table structure for table `restAPI`
-- 

CREATE TABLE `restAPI` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(240) NOT NULL,
  `email` varchar(240) NOT NULL,
  `password` varchar(240) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip` varchar(20) NOT NULL,
  PRIMARY KEY (`id`)
);

Database configuration

Edit database name, user and password as per your configuration

function getConnection() {
    try {
        $db_username = "DATABASE_NAME";
        $db_password = "********";
        $conn = new PDO('mysql:host=localhost;dbname=root', $db_username, $db_password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    } catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
    }
    return $conn;
}

Used PDO connection you can use as per your ease and I have added this function in the same methods file you can also manage them as per your projects.

Why PHP: 12 Reasons to Choose PHP for Developing Website

Implement API

We have created 6 API methods

  1. getUsers
  2. getUser
  3. findByName
  4. addUser
  5. updateUser
  6. deleteUser

Define HTTP routes:

$app->get('/users', 'getUsers'); // Using Get HTTP Method and process getUsers function
$app->get('/users/:id',    'getUser'); // Using Get HTTP Method and process getUser function
$app->get('/users/search/:query', 'findByName'); // Using Get HTTP Method and process findByName function
$app->post('/users', 'addUser'); // Using Post HTTP Method and process addUser function
$app->put('/users/:id', 'updateUser'); // Using Put HTTP Method and process updateUser function
$app->delete('/users/:id',    'deleteUser'); // Using Delete HTTP Method and process deleteUser function
$app->run();

These all routes call an individual function as defined above and in the last $app->run(); used to run Slim application.

let’s see functions:

1. getUsers: $app->get(‘/users’, ‘getUsers’);

function getUsers() {
    $sql_query = "select `name`,`email`,`date`,`ip` FROM restAPI ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt   = $dbCon->query($sql_query);
        $users  = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"users": ' . json_encode($users) . '}';
    }
    catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }    
}

This function simply return all users information as you can see in this query, to call this API use this URL http://localhost/api/users this is it for your first API using get route.

2. getUser: $app->get(‘/users/:id’,    ‘getUser’); In this route we are sending id.

function getUser($id) {
    $sql = "SELECT `name`,`email`,`date`,`ip` FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $user = $stmt->fetchObject();  
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function checks the record of the given id and returns if found anything,  to call this API use this URL http://localhost/api/users/1.

3. findByName: $app->get(‘/users/search/:query’, ‘findByName’); Route is used to search record with extra parameter and a search query with simple get method.

function findByName($query) {
    $sql = "SELECT * FROM restAPI WHERE UPPER(name) LIKE :query ORDER BY name";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);
        $query = "%".$query."%";
        $stmt->bindParam("query", $query);
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_OBJ);
        $dbCon = null;
        echo '{"user": ' . json_encode($users) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This function search in the database for your given query, to call this API use this URL http://localhost/api/users/search/phpgang.

create PHP REST API

4. addUser: $app->post(‘/users’, ‘addUser’); API used to add new record and accept post.

function addUser() {
    global $app;
    $req = $app->request(); // Getting parameter with names
    $paramName = $req->params('name'); // Getting parameter with names
    $paramEmail = $req->params('email'); // Getting parameter with names

    $sql = "INSERT INTO restAPI (`name`,`email`,`ip`) VALUES (:name, :email, :ip)";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("ip", $_SERVER['REMOTE_ADDR']);
        $stmt->execute();
        $user->id = $dbCon->lastInsertId();
        $dbCon = null;
        echo json_encode($user); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API accepts post requests and insert submitted data in your database as we received parameters in starting of that function. To call this API I have used cURL, you can use jQuery or any other technique.

<?php
if($_POST){
    echo post_to_url("http://localhost/users", $_POST);
} else{
 ?>
ADD RECORD.
<form action="" method="post">
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="POST" />
<input type="submit" value="A D D" />
</form>
<?php 
}
?>

This form will be submitted to your action file and there is a curl and that curl will post data as I have used a hidden input of _METHOD with POST value this is because some times your cURL don’t Post data to API (faced this so used this for the post as well) and Slim give us this functionality to method override and as our modern browsers do not have native support to PUT and delete so we have to use method overriding like below.

PHP RESTful API

<input type="hidden" name="_METHOD" value="POST" /> <!-- POST data -->
<input type="hidden" name="_METHOD" value="PUT" /> <!-- PUT data -->
<input type="hidden" name="_METHOD" value="DELETE" /> <!-- DELETE data -->

cURL function to post data:

function post_curl($_url, $_data) {
   $mfields = '';
   foreach($_data as $key => $val) { 
      $mfields .= $key . '=' . $val . '&'; 
   }
   rtrim($mfields, '&');
   $pst = curl_init();

   curl_setopt($pst, CURLOPT_URL, $_url);
   curl_setopt($pst, CURLOPT_POST, count($_data));
   curl_setopt($pst, CURLOPT_POSTFIELDS, $mfields);
   curl_setopt($pst, CURLOPT_RETURNTRANSFER, 1);

   $res = curl_exec($pst);

   curl_close($pst);
   return $res;
}

5. updateUser: $app->put(‘/users/:id’, ‘updateUser’); This route accept put HTTP method.

function updateUser($id) {
    global $app;
    $req = $app->request();
    $paramName = $req->params('name');
    $paramEmail = $req->params('email');

    $sql = "UPDATE restAPI SET name=:name, email=:email WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("name", $paramName);
        $stmt->bindParam("email", $paramEmail);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $status = false;
        if($stmt->rowCount() > 0)
           $status = true;
        $dbCon = null;
        echo json_encode($status); 
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function updates your data by id, to call this API we need to again use cURL and HTML form.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST); // add id after last slash which you want to edit.
} else{
UPDATE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to update" /><br>
<input type="text" name="name" placeholder="Name" /><br>
<input type="text" name="email" placeholder="Email" /><br>
<input type="hidden" name="_METHOD" value="PUT" />
<input type="submit" value="U P D A T E" />
</form>
<?php 
}
?>

6. deleteUser: $app->delete(‘/users/:id’,    ‘deleteUser’); Route used to delete specific ID.

function deleteUser($id) {
    $sql = "DELETE FROM restAPI WHERE id=:id";
    try {
        $dbCon = getConnection();
        $stmt = $dbCon->prepare($sql);  
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $status = false;
        if($stmt->rowCount() > 0)
           $status = true;
        $dbCon = null;
        echo json_encode($status);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}'; 
    }
}

This API function accepts HTTP delete request and to send HTTP delete method we have to used method overriding using our hidden field named _METHOD and the value will be DELETE form and cURL code given below.

<?php
if($_POST){
        echo post_to_url("http://localhost/users/".$_POST['id'], $_POST);
} else{
 ?>
DELETE RECORD.
<br>
<form action="" method="post">
<input type="text" name="id" placeholder="Id to delete" /><br>
<input type="hidden" name="_METHOD" value="DELETE" />
<input type="submit" value="D E L E T E" />
</form>
 <?php 
}
?>

That’s all for one of the biggest tutorials for RESTful API, I hope you like this tutorial, and please don’t forget to give us your feedback and any issue you have faced in this tutorial please do comment we try our level best to solve your problems.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related

  • Tags
  • api
  • How to
  • MYSQL
  • PHP and MySQL
  • RESTful API
  • RESTful Webservice
  • Slim framework
  • Webservice with Slim
Facebook Twitter Google+ LinkedIn Pinterest
Next article Is PHP dead in 2021? Is PHP still relevant or worth the effort?
Previous article 15 websites offering free web developer resources

Huzoor Bux

I am a PHP Developer

Related Posts

How to Extract Text from PDF using PHP PHP
May 17th, 2022

How to Extract Text from PDF using PHP

Is PHP dead in 2021? Is PHP still relevant or worth the effort? PHP
April 3rd, 2022

Is PHP dead in 2021? Is PHP still relevant or worth the effort?

How to Convert HTML to PDF in PHP with fpdf HTML
February 28th, 2022

How to Convert HTML to PDF in PHP with fpdf

2 Comments

  1. yudi
    August 8, 2021 at 3:45 pm Reply ↓

    I download and try..it error 404 Page Not Found

    1. Huzoor Bux
      August 11, 2021 at 7:12 am Reply ↓

      please check .htaccess available in your directory.

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Advertisement
    Like us
    Recent Posts
    • How to Extract Text from PDF using PHP
    • 3 reasons why you SHOULD write tests
    • How to create a screen recorder in JavaScript
    • Best 10 Programming Languages that will rule in 2022
    • Top 7 Websites To Get Your First Paid Internship
    Categories
    • API
    • Bootstrap
    • Bot
    • CSS
    • CSS 3
    • Database
    • Designing
    • Framework
    • Guide
    • HTML
    • HTML 5
    • JavaScript
    • jQuery
    • MySQL
    • Node.js
    • oAuth
    • Payment
    • PHP
    • Python
    • Social
    • Tips
    • WordPress
    Weekly Tags
    • PHP
    • How to
    • javascript
    • api
    • MYSQL
    • jQuery
    • PHP Basics
    • Programming Habits
    • HTML5
    • PHP framework
    • About
    • Privacy Policy
    • Back to top
    © PHPLift 2021. All rights reserved.