PHP : REST API – GET data using cURL

cURL (Client URL) is a tool and a library to transfer data with URLs. It supports HTTP, HTTPS, FTP and more, and it is the most popular way to talk to REST APIs in PHP. The PHP cURL extension is enabled in most installations.


The basic cURL steps

  • curl_init($url): start a cURL session.
  • curl_setopt(): set options, like returning the response as a string.
  • curl_exec(): send the request and get the response.
  • curl_getinfo(): read details like the HTTP status code.
Note: Older tutorials call curl_close() at the end. It is not needed in PHP 8, because the cURL handle is closed automatically when the variable is not used anymore.

GET data from an API

We read the data of user 1 from JSONPlaceholder, as in the previous chapter.

<?php
$url = "https://jsonplaceholder.typicode.com/users/1";

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   // return the response as a string
curl_setopt($ch, CURLOPT_TIMEOUT, 10);            // stop after 10 seconds

$response = curl_exec($ch);

if ($response === false) {
    die("cURL error: " . curl_error($ch));
}

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$user = json_decode($response, true);

echo "Status: " . $status . "<br>";
echo $user["name"];
?>

Output:

Tutorials Class - Output Window

Status: 200
Leanne Graham

How the code works

  • CURLOPT_RETURNTRANSFER is very important. Without it, cURL prints the response directly and does not return it.
  • CURLOPT_TIMEOUT avoids waiting for ever if the API is slow.
  • curl_exec() returns false when the request fails (for example no internet). curl_error() tells the reason.
  • A status code 404 or 500 is not a cURL error. Check the status code yourself.

Useful options

OptionUse
CURLOPT_HTTPHEADERSend headers, like ["Accept: application/json", "Authorization: Bearer YOUR_TOKEN"]
CURLOPT_FOLLOWLOCATIONFollow redirects
CURLOPT_CONNECTTIMEOUTTime to wait while connecting
CURLOPT_USERAGENTSet the user agent text
Note: Never turn off the SSL check (CURLOPT_SSL_VERIFYPEER = false) to “fix” a certificate error. It makes the connection unsafe. Fix the certificate setting of your server instead.

Next chapter: POST data using cURL.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.