0
0
PhpHow-ToBeginner · 3 min read

How to Make API Request in PHP: Simple Guide with Examples

To make an API request in PHP, use the cURL library by initializing a session with curl_init(), setting options like the URL with curl_setopt(), executing the request with curl_exec(), and then closing the session with curl_close(). This lets you send GET or POST requests to APIs and get their responses.
📐

Syntax

Here is the basic syntax to make an API request using cURL in PHP:

  • curl_init(): Starts a new cURL session.
  • curl_setopt(): Sets options like URL, request method, headers.
  • curl_exec(): Executes the request and returns the response.
  • curl_close(): Closes the cURL session to free resources.
php
<?php
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Return response as string
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>
💻

Example

This example shows how to send a GET request to a public API and print the JSON response.

php
<?php
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://jsonplaceholder.typicode.com/posts/1",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPGET => true
]);

$response = curl_exec($curl);
if(curl_errno($curl)) {
    echo 'Error:' . curl_error($curl);
} else {
    echo $response;
}
curl_close($curl);
?>
Output
{"userId":1,"id":1,"title":"sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body":"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
⚠️

Common Pitfalls

Common mistakes when making API requests in PHP include:

  • Not setting CURLOPT_RETURNTRANSFER to true, which causes curl_exec() to output directly instead of returning the response.
  • Forgetting to close the cURL session with curl_close(), which can waste resources.
  • Not handling errors using curl_errno() and curl_error().
  • Incorrectly setting HTTP headers or request methods.
php
<?php
// Wrong way: missing CURLOPT_RETURNTRANSFER
$curl = curl_init("https://jsonplaceholder.typicode.com/posts/1");
curl_exec($curl); // Outputs directly, no variable capture
curl_close($curl);

// Right way:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://jsonplaceholder.typicode.com/posts/1");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
?>
Output
{"userId":1,"id":1,"title":"sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body":"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
📊

Quick Reference

Here is a quick cheat sheet for common cURL options used in API requests:

OptionDescription
CURLOPT_URLThe URL to request
CURLOPT_RETURNTRANSFERReturn response as string instead of outputting
CURLOPT_POSTSet to true to send a POST request
CURLOPT_POSTFIELDSData to send in POST request
CURLOPT_HTTPHEADERArray of HTTP headers to send
CURLOPT_CUSTOMREQUESTSpecify custom HTTP method like PUT, DELETE

Key Takeaways

Use cURL in PHP to make API requests by initializing, setting options, executing, and closing the session.
Always set CURLOPT_RETURNTRANSFER to true to capture the response as a string.
Handle errors by checking curl_errno() and curl_error() after execution.
Close the cURL session with curl_close() to free resources.
Set the correct HTTP method and headers depending on the API requirements.