Hi All,

Today I am going to demonstrate that creating an API (with no authentication) is very easy using PHP.

You require

1. PHP web hosting with MySQL support.
2. Very basic knowledge of PHP.

In this example I have used both JSON and XML response types. Default return type is JSON, if you want XML response add type parameter to your URl e.g.(api.php?type=xml)

To start with creating API you first will need a MySQL database. In case of our example we will be creating a databsae

  1. Create database using query "CREATE DATABASE information".
  2. Create table using query
    "CREATE TABLE IF NOT EXISTS `employee` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `fname` varchar(250) NOT NULL,
    `lname` varchar(250) NOT NULL,
    `email` varchar(250) NOT NULL,
    `address` varchar(250) NOT NULL,
    `mobile` varchar(20) NOT NULL,
    `status` enum('ACTIVE','INACTIVE') NOT NULL,
    `dob` date NOT NULL,
    `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8;"
  3. Insert some dummy values using query
    "INSERT INTO `employee` (`id`, `fname`, `lname`, `email`, `address`, `mobile`, `status`, `dob`, `date_added`) VALUES
    (1, 'aaa', 'eee', 'aaa@test.com', 'test address one', '1234567890', 'ACTIVE', '1990-01-13', '2015-06-11 05:52:09'),
    (2, 'bbb', 'fff', 'bbb@test.com', 'test address two', '1234567890', 'INACTIVE', '1973-06-08', '2015-06-11 05:52:09'),
    (3, 'ccc', 'ggg', 'ccc@test.com', 'test address one', '1234567890', 'ACTIVE', '2000-01-13', '2015-06-11 05:52:24'),
    (4, 'ddd', 'hhh', 'ddd@test.com', 'test address two', '1234567890', 'INACTIVE', '2002-06-08', '2015-06-11 05:52:24');"

I am using PHP version 5.5.x and mysqli to connect to MySQL database. You can find more ways to here PHP Connect to MySQL.

Now we will turn to our php code and here is the code:

<?php
// define your databse connection values
$servername = “”;
$username = “”;
$password = “”;
$dbname = “information”;

/*
* Set default response type that your API will return
*/
$type = “json”;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error)
{
die(“Connection failed: ” . $conn->connect_error);
}

// Define an array to store your records from database
$record = array();

// define you select query
$select = “SELECT id as ID, fname AS FNAME, lname AS LNAME, address AS ADDRESS, email as EMAIL, mobile AS MOBILE, status AS STATUS, dob AS DOB FROM employee where 1”;

// execute query
$result = $conn->query($select);

// find records available or not
if ($result->num_rows > 0)
{
// output data of each row
while ($row = $result->fetch_assoc())
{
array_push($record, array(“ID” => $row[“ID”],
“NAME” => $row[“FNAME”] . ” ” . $row[“LNAME”],
“EMAIL” => $row[“EMAIL”],
“ADDRESS” => $row[“ADDRESS”],
“MOBILE” => $row[“MOBILE”],
“STATUS” => $row[“STATUS”],
“DOB” => $row[“DOB”],
)
);
}
}

// close db connection
$conn->close();

// get your response type
if (isset($_GET[‘type’]) && !empty($_GET[‘type’]))
{
$type = $_GET[‘type’];
}

if (strcasecmp(‘json’, $type) === 0)
{
header(‘Content-Type: application/json’);
echo json_encode($record);
} elseif (strcasecmp(‘xml’, $type) === 0)
{
$string = ‘<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>’;
$string .=”<Employee>”;
foreach ($record as $data)
{
$string .= “<Record>”;
$string .= “<ID>” . htmlspecialchars($data[“ID”]) . “</ID>”;
$string .= “<NAME>” . htmlspecialchars(ucwords($data[“NAME”])) . “</NAME>”;
$string .= “<ADDRESS>” . htmlspecialchars($data[“ADDRESS”]) . “</ADDRESS>”;
$string .= “<EMAIL>” . htmlspecialchars($data[“EMAIL”]) . “</EMAIL>”;
$string .= “<STATUS>” . htmlspecialchars($data[“STATUS”]) . “</STATUS>”;
$string .= “<MOBILE>” . htmlspecialchars($data[“MOBILE”]) . “</MOBILE>”;
$string .= “<DOB>” . $data[“DOB”] . “</DOB>”;
$string .= “</Record>”;
}
$string .=”</Employee>”;
header(‘Content-type: application/xml’);
echo $string;
} else
{
echo “Response format not supported.”;
}

?>

Advertisements