How to add API function to a simple PHP Page ? - GeeksforGeeks

28 Jan, 2020
Application Programming Interface is a system that contains a set of rules or protocols or tools which help in providing interaction between two applications or software by standard data access. It is very much similar to a web service used in developing web pages or mobile apps. One application can call other programs API to utilize some functionality. APIs get requests and return the result in the programmer’s software system.If the system communicates with databases, then the APIs are exposed by PHP extensions.
Examples: Google Maps API, youtube API.
Prerequisites:
PHPPHP cURL library
PHP
PHP cURL library
Program:
<?php  $url = 'RequiredLink';$data = [    'collection'  => 'RequiredAPI'];   $curl = curl_init($url);  function APIcall($method, $url, $data) {    $curl = curl_init();          switch ($method) {        case "POST":            curl_setopt($curl, CURLOPT_POST, 1);            if ($data)                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);            break;        case "PUT":            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");            if ($data)                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);            break;    }         curl_setopt($curl, CURLOPT_URL, $url);    curl_setopt($curl, CURLOPT_HTTPHEADER, array(        'APIKEY: RegisteredAPIkey',        'Content-Type: application/json',    ));         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);    $result = curl_exec($curl);          if(!$result) {        echo("Connection failure!");    }    curl_close($curl);    return $result;}?>
Types of Web APIs: Web APIs are those which are accessible over the internet.
Open APIs: These APIs are publicly available as there is no restrictions.Partner APIs: The user needs license and special rights to access this type of APIs.Private APIs: Owned by companies for internal systems.Composite APIs: Its a combination of data and service APIs for speeding up the execution process.
Open APIs: These APIs are publicly available as there is no restrictions.
Partner APIs: The user needs license and special rights to access this type of APIs.
Private APIs: Owned by companies for internal systems.
Composite APIs: Its a combination of data and service APIs for speeding up the execution process.
Other than the above four, many other APIs are also available. Some APIs are available on the internet, you need not install the software.
Types of Web Service APIs: A very common example, use of payment process API rather than developing our own payment process. Web service APIs are platform-independent methods that are accessed by a network connection.
SOAP: Simple Object Access Protocol which uses web service definition language or XML for data transfer. It is very robust. These are used in integrating APIs.JSON-RPC: For data transfer it uses JSON.REST: The set of rules includes some standard architectural principals for data exchange. For making a request, it uses HTTP methods of getting, PUT, POST, PATCH, DELETE for all CRUD operations. It consumes less bandwidths and also comfortable accessing cloud services.REST output is in the form of JSON:GET: Read or retrieves information.POST: Creates new record.PUT: Update a record.DELETE: Deletes a record.
SOAP: Simple Object Access Protocol which uses web service definition language or XML for data transfer. It is very robust. These are used in integrating APIs.
JSON-RPC: For data transfer it uses JSON.
REST: The set of rules includes some standard architectural principals for data exchange. For making a request, it uses HTTP methods of getting, PUT, POST, PATCH, DELETE for all CRUD operations. It consumes less bandwidths and also comfortable accessing cloud services.REST output is in the form of JSON:GET: Read or retrieves information.POST: Creates new record.PUT: Update a record.DELETE: Deletes a record.
REST output is in the form of JSON:
GET: Read or retrieves information.
POST: Creates new record.
PUT: Update a record.
DELETE: Deletes a record.
Whenever an application uses all four database operations for create, read, update, delete. It is said to have utilized the REST API. All APIs are not web services but all the web services are APIs. A very common example is the REST APIs. REST APIs are backbones of the internet and web services.
The .htaccess file is used for mapping the request URI to the REST API service.
<?phprequire_once("MobileRestHandler.php");  $mobileRestHandler = new MobileRestHandler();$mobileRestHandler->getAllMobiles();?>
GET: Fetch information or data collection. For example product details from a table.$returnData = callAPI(‘GET’, ‘https://api.geeksforgeeks.com/url_for_get/’.$user[‘user’][‘buyer_id’], false);$response = json_decode($returnData, true);$errors = $response[‘response’][‘errors’];$data = $response[‘response’][‘data’][0];
$returnData = callAPI(‘GET’, ‘https://api.geeksforgeeks.com/url_for_get/’.$user[‘user’][‘buyer_id’], false);$response = json_decode($returnData, true);$errors = $response[‘response’][‘errors’];$data = $response[‘response’][‘data’][0];
POST: Adds or creates new information such as feedbacks or reviews of some restaurant.$arrayOfData = array(“buyer” => $user[‘user’][‘buyer_id’],“payment” => array(“accountNumber” => $this->request->data[‘accountNumber’],“routing” => $this->request->data[‘routing’],“method” => $this->request->data[‘method’]),);$apiCall = APIcall(‘POST’, ‘https://api.geeksforgeeks.com/url_for_post/’, json_encode($data_array));$response = json_decode($apiCall, true);$errors = $response[‘response’][‘errors’];$data = $response[‘response’][‘data’][0];
$arrayOfData = array(“buyer” => $user[‘user’][‘buyer_id’],“payment” => array(“accountNumber” => $this->request->data[‘accountNumber’],“routing” => $this->request->data[‘routing’],“method” => $this->request->data[‘method’]),);$apiCall = APIcall(‘POST’, ‘https://api.geeksforgeeks.com/url_for_post/’, json_encode($data_array));$response = json_decode($apiCall, true);$errors = $response[‘response’][‘errors’];$data = $response[‘response’][‘data’][0];
PUT: Updates existing data.$arrayOfData = array(“amount” => ‘RequiredAmount’);$updateData = APIcall(‘PUT’, ‘https://api.geeksforgeeks.com/url_for_put/’.$putParameter,json_encode($arrayOfData));$response = json_decode($updateData, true);$errors = $response[‘response’][‘errors’];$data = $response[‘response’][‘data’][0];
$arrayOfData = array(“amount” => ‘RequiredAmount’);$updateData = APIcall(‘PUT’, ‘https://api.geeksforgeeks.com/url_for_put/’.$putParameter,json_encode($arrayOfData));$response = json_decode($updateData, true);$errors = $response[‘response’][‘errors’];$data = $response[‘response’][‘data’][0];
DELETE: Deletes existing data.APIcall(‘DELETE’, ‘https://api.geeksforgeeks.com/url_for_delete/’ . $required_id, false);
APIcall(‘DELETE’, ‘https://api.geeksforgeeks.com/url_for_delete/’ . $required_id, false);
Using API with PHP cURL:
Get an API key: When you start with APIs, you should register and get a key which is a string of letters and numbers. This API key is only used while making a request so that the server API recognizes the user as a registered user.
Test API with PHP applications: This process checks if everything works as expected.
Develop the required PHP app by using API. Create or develop the application by using necessary APIs.
Steps to create REST API:
Create a database and DB table.Establish database connection.Create a REST API file.Create index or HTML file.Fetch the records from database via cURL
Create a database and DB table.
Establish database connection.
Create a REST API file.Create index or HTML file.Fetch the records from database via cURL
Create index or HTML file.
Fetch the records from database via cURL
PHP-Misc
Picked
PHP
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills