This tutorial aims to provide a detailed guide on how to consume REST APIs using cURL in PHP. By the end of this tutorial, you will be able to retrieve, create, update, and delete data from an API using HTTP requests.
cURL is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, etc.). PHP supports libcurl, which adds the ability for PHP to make cURL requests.
Fetch data from an API using a GET request. This is the most common type of HTTP request, used to retrieve data.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com/api/resource",
CURLOPT_RETURNTRANSFER => true,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
Send data to an API using a POST request. This request is used to create data.
$curl = curl_init();
$data = array(
'key1' => 'value1',
'key2' => 'value2',
);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com/api/resource",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
// Initialize cURL
$curl = curl_init();
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com/api/resource", // API URL
CURLOPT_RETURNTRANSFER => true, // Return the result as a string
));
// Execute the cURL session
$response = curl_exec($curl);
// Close the cURL session
curl_close($curl);
// Print the response
echo $response;
// Initialize cURL
$curl = curl_init();
// Data to be sent
$data = array(
'key1' => 'value1',
'key2' => 'value2',
);
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => "http://example.com/api/resource", // API URL
CURLOPT_POST => true, // Set the request method to POST
CURLOPT_POSTFIELDS => $data, // Set the POST fields
CURLOPT_RETURNTRANSFER => true, // Return the result as a string
));
// Execute the cURL session
$response = curl_exec($curl);
// Close the cURL session
curl_close($curl);
// Print the response
echo $response;
In this tutorial, we've explored how to use cURL in PHP to consume APIs. We learned to make GET and POST requests and handle responses. As next steps, try to make PUT and DELETE requests.
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.publicapis.org/entries",
CURLOPT_RETURNTRANSFER => true,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
$curl = curl_init();
$data = array(
'key1' => 'value1',
'key2' => 'value2',
);
curl_setopt_array($curl, array(
CURLOPT_URL => "http://dummy.restapiexample.com/api/v1/create",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => true,
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;