PHP REST API Tutorial Step by Step [ Beginners ] - Onlyxcodes - onlyxcodes

Tuesday, 24 December 2019

PHP REST API Tutorial Step by Step [ Beginners ] - Onlyxcodes

In this tutorial, you'll learn how to create simple PHP REST API with MySQL without any framework at the beginner's stage. Within this tutorial, I use the core PHP OOPS concept and create REST API on the XAMPP server localhost. Via HTTP method we get and post the API into the POSTMAN tool and getting MySQL data response in JSON format. Let's begin this tutorial pretty easy step by step.


php rest api tutorial step by step for beginners

Table Content

1. What is API?

2. What is REST?

3. File Structure

4. Database and Table Create

5. dbconfig.php

6. index.php

7. .htaccess

8. Extra Points


What is API?

API (Application Programming Interface). It is a set of programming codes that enables data to communicate between one software application to another.


Before we dive into what makes a RESTful API and what criteria and rules you should obey when building RESTful APIs, let's clarify 2 key concepts:


Client– The client is the user of the API or the program. It can be a developer, for instance, you can use the Facebook API as a developer to read and write records from Facebook, create a new post and do more activities in a program you develop.


Your code must call the API of Facebook. The client can be a web browser, too. If you enter the Facebook website, your browser is the client that calls the Facebook API and uses the data that has been returned to display info on the window. 


Resource– Any object the API can provide data regarding can be a resource. For example, a resource in Twitter API can be a user, an image. Every resource has a unique identifier. The identifier can be either a name or a number.  


What is REST?

REST stands for Representational State Transfer. 


That means if a RESTful API is called, the representation of the state of the requested resource will be transferred from the server to the user.


Here,


The HTTP is a stateless protocol that does not hold any recent request data. Using REST API we submit requests for CREATE, READ, UPDATE, DELETE operations using the HTTP protocol, and receive responses in the state. And the state can be in XML or JSON format.


The purpose of REST we create lightweight, maintainable web services.


What the server does when one of its APIs is called by you, the client depends on 2 things you need to provide the server:


1. An identifier of the resource of which you are attracted. This is the resource URL which is also known as the endpoint.


2. The operation you want the server to do it on that resource, as an HTTP method. By following the HTTP method to perform desired end URL operations.   


GET– using that to obtain the data equivalent to READ


POST – using that to create a new record on server or resource equivalent to CREATE


PUT – using that to update data on the server or resource equivalent to UPDATE


DELETE – using that to delete data on the server or resource equivalent to DELETE


File Structure

See below file structure establish within xampp/htdocs/ PHP-REST-API-POSTMAN path location.


PHP-REST-API-POSTMAN/
├── .htaccess
├── dbconfig.php
├── index.php

Database and Table Create

I use a database called 'php_rest_api_db' but you can use any name. After you have created the database insert the following code into your PhpMyAdmin to create the fruits of the table.



CREATE TABLE `tbl_fruits` (
  `id` int(11) NOT NULL,
  `fruit_name` varchar(20) NOT NULL,
  `color` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Dumping data for tbl_fruits table wrapping it up.


INSERT INTO `tbl_fruits` (`id`, `fruit_name`, `color`) VALUES
(1, 'apple', 'red'),
(2, 'banana', 'yellow'),
(3, 'graps', 'green');

dbconfig.php

Create a class called Database, and set up the database connection settings in PHP constructor within this class. if the connection fails then the PDO show issue.


Within this class file call query() function which called from index.php file this line $db->query("SELECT * FROM tbl_fruits") for selects whole records from database table.


If the record found then return statement immediately corporate the execution of a query function.


<?php
class Database
{
 private $pdo;
 
 public function __construct($host,$dbname,$username,$password)
 {
  $con = new PDO ('mysql:host='.$host.'; dbname='.$dbname.';', $username, $password);
  $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $this->pdo = $con;
 }
 public function query($show)
 {
  $stmt = $this->pdo->prepare($show);
  $stmt->execute();
  
  if($show)
  {
   $data = $stmt->fetchAll();
   return $data;
  }
 }
}
?>

index.php

In this file, we include a 'dbconfig.php' file to keep the hostname, database name, username, and password of the database connection utility parts.


create $db object of Database class and via $db object fire SQL select query under in query function. And this function stores in the function json_encode() because that function retrieves JSON format records.


After defining the Database class object $db the constructor will call automatically after constructing the object.


  • 127.0.0.1 – default IP address of XAMPP Server localhost

  • php_rest_api_db  database name

  • root  database username

  • " " – Your password to the database. On my XAMPP server, I do not use any type of password. If you don't use it, do the same.

<?php

require_once('dbconfig.php');

$db = new Database("127.0.0.1", "php_rest_api_db", "root", "");

if($_SERVER["REQUEST_METHOD"]=="GET")
{
 echo json_encode($db->query("SELECT * FROM tbl_fruits"));
}
else if($_SERVER["REQUEST_METHOD"]=="POST")
{
 echo "This is POST ";
}
else
{
 http_response_code(405);
}

?>

.htaccess

Using this file codes to remove index.php extension on URL. Please file must be saved with .htaccess extension.


<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L] 
</IfModule>

OK, execute project and type to create this REST API URL http://localhost/PHP-REST-API-POSTMAN/tbl_fruits


Note: End of URL the tbl_fruits database table name.


Let’s check the REST API on the Postman tool.


Copy URL from localhost XAMPP Server,


Copy REST API URL form localhost XAMPP Server


Paste into the Postman tool and follow the below step I mentioned in screenshots.


REST API URL paste into the Postman tool and using the HTTP GET method getting MySQL data in JSON format.

Also, check with this simple REST API with the POST method.


Also, check the REST API with the POST method.

Extra Points:-


$_SERVER['REQUEST_METHOD'] =='GET' determines whether the request was  GET.


$_SERVER['REQUEST_METHOD'] =='POST' determines whether the request was POST.


405 Is status codes that we use not allowed for method. Friends lots of available status codes please read notes on Wikipedia website.



Download Codes

3 comments:

  1. अमित पुरोहित4 January 2020 at 12:48

    हेल्लो सर, क्या आप वेबसाइट बनाने काम करते है क्लाइंट्स के लिए क्युकी मुझे एक वेबसाईट बनवानी है अगर आप बोलते हो तो में आपसे बनवालूँगा, आप जो भी चार्ज करते हो में दे दूंगा. ?

    ReplyDelete
  2. Hey, Amit thanks,

    But currently, I'm busy on blogging if you face any problem with your project send me, I try to solve your problem.

    Cheers

    ReplyDelete
  3. I have read your blog on create RESTful APIs with PHP. It was very interesting and helpful but I can add some extra points in your article. Here some extra points:
    1.Create a database and DB table.
    2.Establish database connection.
    3.Create a REST API file. Create index or HTML file. Fetch the records from database via cURL.
    These are some extra points to add to your article. Readers if you are confused about your web and App development , you can get a free consultation at Alakmalak technologies.Visit our site for more information.

    ReplyDelete

Post Bottom Ad