Creates a simple api in php

In today world use of api has beeen increased. People makes api he and these is used in website, android app and iso app.

Now peoples are using apis in website development instead of direct html from a server side script. they fetch json or xml data from api and then parse that data vai javascript libarary and render the output in html.

Peoples are doing this because, this time most of customers want to use same database logic for their website, android app and ios app.

So the importance of api has been increased. Apis can be created in any server side scripting language like Php, Python and NodeJs etc.

Here we will see a very short example of api using php and Mysql. Our objective is to create an api that accepts user_id as parameter and return the user detail in json format.

First of of all we will create a table in mysql. you can create this table vai phpmyadmin.
Run below sql query in the Phpmyadmin.

CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(20) NOT NULL,
`last_name` varchar(20) NOT NULL,
`email` varchar(50) NOT NULL,
`mobile` varchar(50) NOT NULL,
`address` varchar(50) NOT NULL,
`city` varchar(20) NOT NULL,
`state` varchar(20) NOT NULL,
`country` varchar(20) NOT NULL,
`created` date NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Php can be returned output in many formats. like html, Image, Json or Xml etc.
if you write code in Php file that return output in Json or Xml format then this file can be used an Api.

Below is the code of a Php file that is returning Json output.

<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'pass';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("api_sample");

$output = array();

if(isset($_REQUEST['id'])) {
$id = $_REQUEST['id'];
}else {
$err = 1;
$error_msg = "Please provide user id";
}

if($err == 1) {
$output['status'] = 1100;
$output['msg'] = "failed";
$output['data'] = $error_msg;
print json_encode($output);
die;
}

$sql = "select * from users where id = '$id'";

$result = mysql_query($sql);

$results = array();
while($row = mysql_fetch_assoc($result)) {
$results[] = $row;
}

mysql_close($conn);

$output['status'] = 200;
$output['msg'] = "OK";
$output['data'] = $results;
print json_encode($output);

?>

We have used status 200 which means ok. We should use proper status codes in api output.
like when error occurs or validation failed we should give proper status code and error messages. Status code make it easy to handle api data on front side.

Leave a Reply

Your email address will not be published. Required fields are marked *

5 × 5 =