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.
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?
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.
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.
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:
- An identifier of the resource of which you are attracted. This is the resource URL which is also known as the endpoint.
- 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.
File Structure
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;
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.
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.
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.
RewriteEngine On RewriteCond % !-f RewriteCond % !-d RewriteRule ^(.*)$ index.php/$1 [L]
OK, execute project and type to create this REST API URL http://localhost/PHP-REST-API-POSTMAN/tbl_fruits
$_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.