Skip to content
Home » Fetch Data from API: 3 PHP Options with Code Examples in 2023

Fetch Data from API: 3 PHP Options with Code Examples in 2023

How to Fetch Data from a REST API with PHP

There are 3 options to fetch data from a REST API with PHP. The recommended approach is to use the Guzzle composer plugin for most situations because it provides an object-oriented solution. You can also use the file_get_contents PHP function and use the cURL library as well.

In this article, we will learn how to fetch data from an API in PHP. We will explain two popular methods( using file_get_contents() function and PHP cURL functions) for fetching data from an API in PHP. We will also discuss what an API is and the types of web APIs. 

Article Highlights

  • Use the Guzzle Composer whenever possible because it allows for better extensibility, testing & follows an object-oriented approach
  • The file_get_contents function can be used for very simple use cases
  • The cURL PHP library is a good solution whenever you aren’t able to work with Guzzle or need extreme flexibility.

Example code to Fetch Data from a REST API in PHP

<?php


$rest_api_url = 'https://dummy.restapiexample.com/api/v1/employees';


// Reads the JSON file.
$json_data = file_get_contents($rest_api_url);


// Decodes the JSON data into a PHP array.
$response_data = json_decode($json_data);


// All the users data exists in 'data' object
$user_data = $response_data->data;


// It cuts the long data into small & select only the first 5 records.
$user_data = array_slice($user_data, 0, 5);


// Print data if need to debug


// It traverses the array and display user data
foreach ($user_data as $user) {
  echo "name: ".$user->employee_name;
  echo "<br />";
  echo "Age: ".$user->employee_age;
  echo "<br /> <br />";
}
?>

how to fetch data from api in php

Table of Contents

In this article, we will discuss the following topics.

  1. What is a REST API?
  2. Using the file_get_contents() Function
  3. Using cURL With PHP to Fetch Data
  4. Using the Guzzle Composer Package
  5. Fetching Data from API Summary

What is a REST API

A REST API is a medium of communication between systems on the internet. REST APIs are widely used in web and mobile applications. These APIs can provide output data in multiple formats such as JavaScript Object Notation (JSON), Extensible Markup Language (XML), Command Separated Value (CSV) and many others. 

These APIs also use HTTP methods such as GET, HEAD, POST, PUT, and DELETE to perform different operations.

In this article, we will explain how to fetch data from REST APIs in PHP. We can use PHP built-in function file_get_contents() function or PHP cURL library commands to fetch data from a REST API in PHP.

Working with JSON data in an API

XML & JSON are the two mostly used API data formats. This article will use an API that works with JSON data.

It is very easy to read or get data from the REST API URL, but most applications create dedicated URLs to provide access to their data for other applications.

Most APIs use the HTTP GET method to read API data, and we can simply hit the URL in the browser to view data for testing. It is because when you HIT any URL in the browser, it sends a GET request and access data. You can also search for dummy or sample REST API URLs online for testing.

A Sample JSON data format in APIs

This article uses the Dummy REST API example website to work with live API data in our code examples. This website provides many routes or URLs to read, create, update, and delete data using API. We will use the following API to read employee data.

To GET the employee data, we use this API URL: http://dummy.restapiexample.com/.

The above URL provides the employee’s profile data in JSON format, which looks like this.

[{"id":"300","employee_name":"Robin","employee_salary":"54000","employee_age":"5"},
{"id":"101","employee_name":"John","employee_salary":"12350","employee_age":"29"},
{"id":"114","employee_name":"Roy","employee_salary":"90000","employee_age":"18"}

Using the file_get_contents() Function to Fetch Data From Rest a API

The file_get_contents PHP function is the simplest way to fetch data from a REST API. I only recommend this approach when you have very basic requirements or running a test. You will find this approach problematic for anything of complexity, such as pagination or needing to model the return data.

That being said, I still use the file_get_contents() function when it comes to simple requirements. We showcase the usage of it below.

In the following PHP code example, we used a sample API URL that provides employees’ data and displays them.

<?php


$rest_api_url = 'https://dummy.restapiexample.com/api/v1/employees';


// Reads the JSON file.
$json_data = file_get_contents($rest_api_url);


// Decodes the JSON data into a PHP array.
$response_data = json_decode($json_data);


// All the users data exists in 'data' object
$user_data = $response_data->data;


// It cuts the long data into small & select only the first 5 records.
$user_data = array_slice($user_data, 0, 5);


// Print data if need to debug


// It traverses the array and display user data
foreach ($user_data as $user) {
  echo "name: ".$user->employee_name;
  echo "<br />";
  echo "Age: ".$user->employee_age;
  echo "<br /> <br />";
}


?>

Output:

name: Tiger Nixon<br />
Age: 61<br /> <br />
name: Garrett Winters<br />
Age: 63<br /> <br />
name: Ashton Cox<br />
Age: 66<br /> <br />
name: Cedric Kelly<br />
Age: 22<br /> <br />
name: Airi Satou<br />
Age: 33<br /> <br />

In the above code, we passed the API URL in file_get_contents() to fetch the data of the employees. We also use the json_decode() function to decode JSON data into a PHP array. 

In the above example, we only select the first 5 records by slicing the array because given feed data is large, this may slow down your browser to show them all. We also traverse the user data array using the foreach method and display the result.

In PHP, using the file_get_contents() function, we can only read files or API data but can not perform write, update, or delete operations. 

Using PHP cURL methods with REST APIs in PHP

cURL is the right option to fetch data from REST APIs when you have complicated requirements. There are many options and parameters that are available when using the cURL library. Most servers have the cURL extension installed with PHP, but you should confirm with your provider.

In this section, we will learn how to fetch data from an API using PHP cURL functions. 

We will use the cURL GET method to get data, POST method to create data, PUT method to update data, and DELETE method to delete data from an API in PHP.

Want to learn more about cURL? We have a full learning path on the topic. Click here to learn more about cURL.

Using cURL GET method to get data from an API

To get data from an API using cURL, you need to perform the following steps:

  1. initialize a cURL session using $curl_handle = curl_init();
  2. Pass the URL option in the cURL session curl_setopt($curl_handle, CURLOPT_URL, $url);
  3. Execute cURL session & store data: $api_data = curl_exec($handle);
  4. In the end, close the cURL session: curl_close($curl_handle);

We will use the same dummy data that we used in the above example. http://dummy.restapiexample.com/.

In the following PHP code, we will use PHP cURL function to get data from a REST API and display the result.

Fetch Data from Rest API with cURL PHP Code Example

<?php
//We initiate a curl session in a variable (resource).
$curl_handle = curl_init();


$url = "https://dummy.restapiexample.com/api/v1/employees";


// Now, we set the curl URL option
curl_setopt($curl_handle, CURLOPT_URL, $url);


// This option returns data as a string instead of direct output
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);


// Execute curl & store data in a variable
$curl_data = curl_exec($curl_handle);


curl_close($curl_handle);


// Decodes the JSON into a PHP array.
$response_data = json_decode($curl_data);


// All user data exists in 'data' object.
$user_data = $response_data->data;


// We extract only the first 5 user data (or 5 array elements).
$user_data = array_slice($user_data, 0, 5);


// Traverses an array and prints employee data.
foreach ($user_data as $user) {
  echo "name: ".$user->employee_name;
  echo "<br />";
}
?>

Output:

name: Tiger Nixon<br />
name: Garrett Winters<br />
name: Ashton Cox<br />
name: Cedric Kelly<br />
name: Airi Satou<br />

In the above code, first, we initiated a cURL and passed the API URL. Then we executed the cURL and stored the received data. As the API URL returns JSON data, we decoded it using the json_decode() function. Now we have all data as an array which we can traverse using foreach and display the result.

Using Guzzle to fetch data from an API in PHP

Guzzle is the recommended way to fetch data from an API. It is a composer package that wraps the cURL library into object-oriented methods. Guzzle makes fetching data testable and extendable. It is the standard for data fetching. You should only use the other methods when you are unable to use Composer.

This article assumes that you already know how to install Composer and additional packages.

Fetching Data from API with Guzzle Package Code Example

To make a GET request, we create an instance of the Client class. And then, we prepare an instance of the Request class, where we indicate the URL we will open and send the request.

<?php


require_once 'vendor/autoload.php';


use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;


$client = new Client();


// We prepare the Request.
$request = new Request('GET', 'https://www.example.com');


// Sends a Request
$response = $client->send($request);


// Read the Response.
$response_body = (string)$response->getBody();
var_dump($response_body);
?>

Using Guzzle GET Request with URL Parameters

Now, to send parameters to the URL, we can use two methods to choose from. We can put the parameters next to the URL or define them in an array that we pass as an option named query on the send method. Both methods are given below in the example code.

<?php
require_once 'vendor/autoload.php';


use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;


$client = new Client();


// Method 1
$request = new Request('GET', 'https://www.example.com?param1=value1&param2=value2');
$response = $client->send($request);


// Method 2
$request = new Request('GET', 'https://www.example.com');
$response = $client->send($request, [
    'query' => [
        'param1' => 'value1',
        'param2' => 'value2'
    ]
]);


// Read Response
$response_body = (string)$response->getBody();
var_dump($response_body);
?>

How to Fetch Data from an API Using PHP

Guzzle, cURL & file_get_contents are the 3 methods to fetch data from a REST API in PHP. Using Guzzle as a composer package is the recommended method. cURL is an option if Guzzle isn’t available. The function file_get_contents should only be used for simple use cases.

Recommendations:

  1. The Guzzle Composer Plugin is our top recommendation for fetching data
  2. Use the file_get_contents method whenever you have very simple requirements
  3. You can use the cURL library whenever you have complex requirements

Continue Learning About cURL

This article is part of a more extensive series on using cURL in PHP. Feel free to browse through the articles to dig deeper into the topic.

Related API Integration Articles

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started