Open In App

How to add API function to a simple PHP Page ?

Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. PHP
  2. PHP cURL library

Program: 

php




<?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.

  1. Open APIs: These APIs are publicly available as there is no restrictions.
  2. Partner APIs: The user needs license and special rights to access this type of APIs.
  3. Private APIs: Owned by companies for internal systems.
  4. 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.

  1. 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.
  2. JSON-RPC: For data transfer it uses JSON.
  3. REST: The set of rules includes some standard architectural principles 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.

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. 

php




<?php
require_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];

  • POST: Adds or creates new information such as feedback 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];

  • 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];

  • DELETE: Deletes existing data.

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:

  1. Create a database and DB table.
  2. Establish database connection.
  3. Create a REST API file.
    • Create index or HTML file.
    • Fetch the records from database via cURL


Last Updated : 03 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads