Get api response php

PHP : REST API – GET data using cURL

In this tutorial, we will learn how to GET API data using cURL functions.

What is cURL?

cURL (stands for client URL) is a command-line tool to transfer data between servers. It supports various protocols such as HTTP, HTTPS, FTP, FTPS, IMAP etc. Most programming languages support cURL commands using some libraries or extension.

cURL is one of the popular methods to interact with REST API data. PHP use cURL library (module) to provide access curl functions within PHP. By default, most PHP installations come with cURL support is enabled.

How to use cURL in PHP

The basic process of PHP cURL can be divided into four parts.

  • Initialize a cURL session using $curl_handle = curl_init();
  • Pass URL option in the cURL session curl_setopt( $curl_handle, CURLOPT_URL, $url );
  • Execute cURL session & store data: $api_data = curl_exec($handle) ;
  • Close cURL session: curl_close( $curl_handle );

Sample REST API data in JSON

We will use Dummy REST API Example website to work with live API data in our examples. This website provides a number of routes or URLs to read, create, update, delete employee’s data using API. We will use following to get employees data.

Above URL provides employee’s profile data in JSON format something similar to following:

PHP program to GET REST API data using cURL

In the following PHP program, we will use a sample PHP CURL function to get employee’s data and displays them.

data; // Extract only first 5 user data (or 5 array elements) $user_data = array_slice($user_data, 0, 4); // Traverse array and print employee data foreach ($user_data as $user) < echo "name: ".$user->employee_name; echo "
"; > ?>

Code Explanation

First, we need to initiate a curl and pass your API URL. Then execute CURL & store received data. As API URL returns JSON data, we need to decode it using json_decode. Now you have all data as an array which you can traverse using foreach and display accordingly.

Читайте также:  Beginning html and css code

In the next chapters, we will use cURL methods to perform an update, create and delete operations using API data.

Источник

Consuming RESTful Web Services using PHP

In our previous tutorial, we have explained how to Make Simple RESTful API with PHP. In this tutorial, we will explain how to consume RESTful API using PHP.

REST (Representational State Transfer) API has been getting popularity as it’s very simple and easy to use. The REST is stateless architecture that generally consists of clients, servers and HTTP operations known as request methods (GET, POST, PUT, DELETE).

Currently most of web applications are implemented with REST API as it’s best solution when the same data used by different applications. If you’re a PHP developer, you’re well aware about the importance of REST API when developing mobile applications.

So if you’re developing web application using REST API and looking for solution to consume RESTful web services, then you’re here at right place.

We will cover this tutorial step by step to consume RESTful API methods (GET, POST, PUT, DELETE) with live REST API examples. As in our previous REST API tutorial, we have created RESTFul API with (GET, POST, PUT, DELETE) to perform operation on product data. So we will consume this RESTful API in this example.

Step1: Create Function To Call REST API Methods

If you’re implementing a web application with REST API, you just need an API call for different methods. So we need to create a simple PHP function to allow REST API HTTP calls for different methods. We will create a function requestApi($method, $apiUrl, $data) with three parameters to make REST API HTTP request for different methods (GET, POST, PUT, DELETE) and get response.

function requestApi($method, $apiUrl, $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; default: if ($data) $apiUrl = sprintf("%s?%s", $apiUrl, http_build_query($data)); >curl_setopt($curl, CURLOPT_URL, $apiUrl); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'APIKEY: 123456789', 'Content-Type: application/json', )); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $resultData = curl_exec($curl); if(!$resultData) < die("Invalid API Request!"); >curl_close($curl); return $resultData; >

Step2: Make GET Method REST API Call

We will make API call with GET method to get all product records. We will call method requestApi() and pass three parameters API request method, API URL and data if needed. As there are no need set data with GET API call, so we just pass it as false. The function requestApi() will make HTTP request and get all products response data.

Читайте также:  Json object to file php

We can also make API call for a specific product by just passing product id.

Step3: Make POST Method REST API Call

We will make API call with POST method using function requestApi() with details to create a new product record. We will pass required POST data as JSON data to create a new product record. As the API POST method require JSON data, so we always need to pass JSON data otherwise it will return error. The response data will have API request status.

 "1234567ui", "category_id"=> 3, "product_name"=>"Camera", "price"=>"$4000", "brand"=>"Sony", "material"=> "Steel", "size"=>30, "qty"=> 12, "created_date"=> "2019-10-27 04:30:00" ); $response = requestApi('POST', 'https://coderszine.com/demo/api/product/create.php', json_encode($postData)); print_r($response); ?>

Step4: Make PUT Method REST API Call

We will make PUT method REST API call using function requestApi() with JSON data to update the existing product record. We will JSON data with update values and product id to update the specific record.

 17, "sku_id"=> "1234567ui", "category_id"=> 3, "product_name"=>"Nice CAmera", "price"=>"$5000", "brand"=>"Sony", "material"=> "Steel", "size"=>30, "qty"=> 12, "created_date"=> "2019-10-27 04:30:00" ); $response = requestApi('PUT', 'https://coderszine.com/demo/api/product/update.php', json_encode($data)); print_r($response); ?>

Step5: Make DELETE method REST API Call

We will make DELETE method API call by using requestApi() function and pass JSON data with product id to delete it.

 17 ); $response = requestApi('PUT', 'https://coderszine.com/demo/api/product/delete.php', json_encode($data)); print_r($response); ?>

Step6: Conclusion

This is a simple tutorial to consume simple RESTful API with methods (GET, POST, PUT, DELETE) using PHP. You can also make changes to this API call method to use flexible headers etc according to your requirement.

You may also like:

  • Follow and Unfollow System with PHP & MySQL
  • GST Billing System with PHP & MySQL
  • Restaurant Management System with PHP & MySQL
  • Visitor Management System with PHP & MySQL
  • Student Attendance System with PHP & MySQL
  • Like and Dislike System with Ajax, PHP & MySQL
  • Build Star Rating System with jQuery, PHP & MySQL
  • User Registration and Login System with PHP & MySQL
  • Build Contact Form with PHP and Ajax
  • To-do List Application with Ajax, PHP & MySQL
  • Build Event Calendar with jQuery , PHP & MySQL
  • Create Dynamic Bar Chart with JavaScript, PHP & MySQL
  • Drag And Drop File Upload with jQuery and PHP
  • Drag and Drop Reorder with jQuery, PHP & MySQL
  • Data Export to Excel with PHP and MySQL
  • Multiple Image Upload with jQuery, PHP and MySQL
  • Create Ajax Pagination with PHP and MySQL
  • jQuery Datatables Server Side Processing with PHP & MySQL
  • Editable HTML Table with jQuery, PHP & MySQL
  • Filter Search Result with Ajax, PHP & MySQL
  • Image Crop and Upload using jQuery and PHP
  • Live Datatables CRUD with Ajax, PHP & MySQL
  • Create REST API with PHP & MySQL
  • Build Dynamic Image Gallery with PHP & MySQL
  • Implement jQuery Bootgrid with PHP & MySQL
  • Multiselect Dropdown with Checkbox using jQuery and PHP
  • Autocomplete Search with Bootstrap, PHP & MySQL
Читайте также:  Python exception new line

Источник

Оцените статью