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

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

How to Fetch Data from a REST API with PHP

There are three options to fetch data from a REST API with PHP. The Guzzle composer package is the recommended approach. The PHP cURL library and file_get_contents function are also options available as well.

Example code to Fetch Data from a REST API in PHP

<?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);
?>

Options to Get Data From API in PHP Comparison Table

Featurefile_get_contentscURLGuzzle (Composer Package)
Ease of UseSimple and concise.Requires more codeWell-documented and user-friendly.
HTTP MethodsSupports GET and POST.Supports various methods (GET, POST, PUT, etc.)Supports various methods (GET, POST, PUT, etc.)
Request HeadersLimited control over headers.Full control over headers.Full control over headers.
Response HandlingProvides the response as a string.Requires manual parsing.Provides a more structured response object.
Error HandlingLimited error handling.Requires manual error handling.Provides detailed error handling.
HTTP AuthenticationLimited options for authentication.Supports various authentication methods.Supports various authentication methods.
TimeoutsLimited control over timeouts.Allows setting connection and request timeouts.Allows setting connection and request timeouts.
Concurrent RequestsNot suitable for concurrent requests.Supports concurrent requests.Supports concurrent requests with ease.
MiddlewareNo built-in middleware support.No built-in middleware support.Provides a middleware system for custom processing.
SSL SupportLimited SSL support.Provides strong SSL support.Provides strong SSL support.
Proxy SupportLimited proxy support.Supports proxy configuration.Supports proxy configuration.
CustomizationLimited customization options.Highly customizable.Highly customizable.
Third-Party LibrariesNo additional libraries required.Can be used standalone or with third-party libraries.Requires the Guzzle library via Composer.
Community & SupportWidely used with ample online resources.Well-established with extensive documentation.Active community and extensive documentation.
RecommendationSimple requests, small-scale projects.More control, mid to large-scale projects.Scalable, robust, and suitable for most projects.

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 can’t work with Guzzle or need extreme flexibility.

Links to Official Docs

Table of Contents

In this article, we will discuss the following topics.

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

Using the file_get_contents() Function to Fetch Data From the Rest 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 for 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. Some many options and parameters 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.

Latest cURL Articles on CraftyTechie

using Guzzle vs cURL: How to Choose the Right One in 2023

Discover the key differences between Guzzle vs cURL and find out which one is the best fit for your project. Read our detailed comparison.

Using cURL with Bearer Authorization Tokens PHP Code Examples

Master cURL & Bearer Tokens in PHP: Our comprehensive guide with PHP Code Examples for Using Bearer Authorization Tokens with cURL.

Using cURL with Self-Signed Certificates: PHP Code Examples

Secure your PHP applications with curl self signed certificate. Learn more about using cURL with self-signed certificates with code examples.

Using the DELETE HTTP Method with cURL | PHP Code Examples

Learn how to delete data from your RESTful API using PHP cURL DELETE HTTP method and explore our comprehensive step-by-step guide.

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 cannot use Composer.

This article assumes you 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 three 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

Related API Integration Articles

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.