How to Make a cURL API Request in PHP

Make cURL API requests in PHP with headers, methods, payloads, responses, and third-party integration basics for developers.

How to Make a cURL API Request in PHP cover image

Learn how to send API requests using PHP's cURL extension, perfect for third-party API integrations and modern web development workflows.

When I first started integrating third-party APIs into my PHP applications, I quickly realized that understanding cURL was not optional. Whether I needed to connect to a payment gateway, fetch remote JSON data, authenticate users through an external provider, or sync information between platforms, PHP’s cURL extension became one of the most important tools in my stack. In this guide, I will walk through how I use cURL in real-world scenarios, focusing on clean, practical examples that you can immediately adapt to your own projects.

What Is cURL in PHP?

cURL is a client-side URL transfer library that allows PHP to communicate with external servers using various protocols such as HTTP and HTTPS. In practical terms, it enables me to send GET, POST, PUT, or DELETE requests to APIs and retrieve responses programmatically.

Most modern APIs are REST-based and return JSON. With cURL, I can send structured requests, attach authentication headers, transmit JSON payloads, and handle server responses securely. For any serious PHP application that interacts with third-party services, mastering cURL is essential.

Basic GET Request Example

A GET request is the simplest form of API communication. I use it whenever I need to retrieve data from an external endpoint without sending additional payload data.

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, "https://api.example.com/data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

In this example, I initialize a cURL session, define the target URL, and enable CURLOPT_RETURNTRANSFER so the response is returned as a string instead of being directly output. After executing the request, I close the connection and display the response.

This pattern is commonly used to fetch public API data such as exchange rates, weather information, or remote configuration values.

Adding Headers for Authentication

Most production APIs require authentication. Typically, I need to include an API key or bearer token in the request headers. cURL allows me to define custom headers easily.

<?php
$ch = curl_init("https://api.example.com/user");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer YOUR_API_KEY",
    "Accept: application/json"
]);

$response = curl_exec($ch);
curl_close($ch);

$data = json_decode($response, true);
print_r($data);
?>

Here, I pass an Authorization header along with an Accept header indicating that I expect JSON. After receiving the response, I decode it into an associative array using json_decode(). This is a standard workflow when working with secure REST APIs.

Sending a POST Request with Form Data

Whenever I need to submit data to an API endpoint, I use a POST request. This is common when creating users, submitting forms, or sending structured information to a remote service.

<?php
$data = [
    "name"  => "John",
    "email" => "[email protected]"
];

$ch = curl_init("https://api.example.com/submit");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

In this case, I use http_build_query() to properly encode the data as application/x-www-form-urlencoded. This format is widely supported and ideal for traditional form submissions.

Sending JSON Payloads with cURL

Modern APIs often expect raw JSON instead of form-encoded data. When I integrate with services like authentication systems, SaaS platforms, or microservices, sending JSON is usually mandatory.

<?php
$data = json_encode([
    "username" => "demo",
    "password" => "secret"
]);

$ch = curl_init("https://api.example.com/login");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Content-Length: " . strlen($data)
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
?>

Here, I explicitly set the Content-Type header to application/json. This ensures the receiving API correctly interprets the payload. Sending JSON is now the standard approach in RESTful API development.

Proper Error Handling in cURL

One mistake I see frequently is ignoring error handling. When working with external APIs, failures can occur due to network issues, invalid credentials, server downtime, or malformed requests. I always check for errors immediately after executing a cURL request.

<?php
$ch = curl_init("https://api.example.com/test");

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo "cURL error: " . curl_error($ch);
} else {
    echo $response;
}

curl_close($ch);
?>

Using curl_errno() and curl_error() helps me quickly diagnose connection or request issues. In production applications, I typically log these errors instead of displaying them directly.

Best Practices for Using PHP cURL

Over time, I have adopted a few best practices when working with cURL in PHP. First, I always enable SSL verification in production environments to ensure secure communication. Second, I abstract repeated cURL logic into reusable functions or service classes to keep my codebase clean and maintainable. Third, I validate and sanitize all outgoing and incoming data to reduce security risks.

cURL remains one of the most reliable and flexible tools for API integration in PHP. Whether I am building a simple data-fetching script or a complex microservice architecture, understanding how to properly configure GET and POST requests, handle JSON payloads, manage headers, and process errors gives me full control over external communications.

Mastering PHP cURL allows me to confidently integrate third-party services, automate workflows, and build scalable web applications that communicate efficiently with external APIs.