API-PHP
API, an abbreviation of application program interface, is a set of routines, protocols, and tools for building software applications.
This instructable will explain how to create simple API with PHP.
Requirements
- Basic knowledge of PHP and Database.
- Simple logics (if,switch)
- server/localhost
- IDE/Text Editor
Server/localhost & Client
its better to use localhost like xampp,mampp,wampp or direct install of apache and mysql
I am using xampp on Ubuntu 14.
- Start apache and mysql from manage servers tab.
- Create project folder in your htdocs or or apache /var/www/html
- windows users it will be in your apache or xampp installation folder .(commonly in C:)
IDE
Any text editor or IDE like Aptana Studio,Dreamweaver,Sublime,notepad++.
Coding
In php everything execute in server side and echoed or printed output will be displayed as text.
Header information is very important, else client will not understand how to process the info.
we will be giving output as JSON .
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript.
API must accept incoming request from any type of client . Some API's are only configured as accept certain device or only web browsers.
header('Access-Control-Allow-Origin: *'); // for accepting any origin like localhost ,other.
header('Content-Type: application/json'); //setting header as JSON
Then processing given information.
- Getting parameters from POST/GET type.
- Switching case or if conditions depend on input.
- Storing / retrieving Data from DB or FILE
- Display the output.
Process Info
For example
passing action and info via GET method.
http://yourdomain.com/api.php?action=time
so defined action is time , code will be
$action = $_GET['action'];
switching the action
switch($action){case "time":
//action code
break;
}
Output
Printing output as JSON
echo json_encode(array("title"=>data));
so total code will be
<?php
header('Access-Control-Allow-Origin: *'); // for accepting any origin like localhost ,other.header('Content-Type: application/json'); //setting header as JSON $action = $_GET['action']; switch($action){ case "time": $data=time(); //inbuilt time function in php returns UNIX timestamp break;
case "store":
//Store another input in db or file
break;
}
echo json_encode(array("result"=>$data));
?>
so when you call
yourdomain.com/api.php?action=time
result will be
{"result":"1440237956"}