In this article will see how we can create a simple rest api with php. This tutorial will help you know how to output data into JSON format. As the below code only show you how to create rest api and it does not focus on any security. This article is only to help you know and create a basic Rest API with the help of PHP and MySQL.
As PHP works server side. We have WAMP Server installed in our windows system.
Steps and Source code for Creating a Rest API in PHP –
– First lets create a database
CREATE DATABASE testapi;
– Second step is to create table
CREATE TABLE IF NOT EXISTS `image_slider` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(64) NOT NULL, `description` varchar(255) NOT NULL, `image_url` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
– After creating our database and table. Add data to the table.
INSERT INTO `image_slider` (`id`, `title`, `description`, `image_url`) VALUES (1, 'Slide 1', 'First of three slides', 'http://localhost/sliderimg/slide1.png'), (2, 'Slide 2', 'Second of three slides', 'http://localhost/sliderimg/slide2.png'), (3, 'Slide 3', 'Third of three slides', 'http://localhost/sliderimg/slide3.png');
– Now we will create php file (testapi.php) to output the data into JSON format.
<?php header("Content-type:application/json"); $con = mysqli_connect("127.0.0.1", "root", "", "testapi"); if(!$con){ die('Could not connect: '.mysqli_error()); } $result = mysqli_query($con, "SELECT * FROM image_slider"); while($row = mysqli_fetch_assoc($result)){ $output[]=$row; } print(json_encode($output, JSON_PRETTY_PRINT)); mysqli_close($con); ?>
– This is the output you will get after running our php file (http://localhost/testapi.php).
[ { "id": "1", "title": "Slide 1", "description": "First of three slides", "image_url": "http:\/\/localhost\/sliderimg\/slide1.png" }, { "id": "2", "title": "Slide 2", "description": "Second of three slides", "image_url": "http:\/\/localhost\/sliderimg\/slide2.png" }, { "id": "3", "title": "Slide 3", "description": "Third of three slides", "image_url": "http:\/\/localhost\/sliderimg\/slide3.png" } ]
Hope you find this article helpful. Join us on Facebook, Twitter and Google+ to get more updates on Android and Web Development Tutorials.