PHP cURL Guide: Handle API Requests (GET, POST, PUT, DELETE)

Making API calls from PHP is essential when working with remote services. Using cURL, you can easily send requests of various types such as GET, POST, PUT, and DELETE by writing a flexible utility function. Here’s how:

function callApiMethod($method, $url, $data = array()) {
    $curl = curl_init($url);
    switch ($method) {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    $result = curl_exec($curl);
    if (!$result) {
        die("Connection Failure");
    }
    curl_close($curl);
    return $result;
}

Function Overview

  1. The callApiMethod() function abstracts cURL usage for various HTTP methods.
  2. It smartly adjusts settings based on the method like POST, PUT, etc.
  3. Appends query parameters for GET or sends payloads for POST/PUT.
  4. Handles connection failures with a fallback message.

Working Examples

Use the function like this in your code:

// GET example
$response = callApiMethod('GET', 'https://api.example.com/users/123');
var_dump($response);

// POST example
$data = array('name' => 'Jane Doe', 'email' => 'jane@example.com');
$response = callApiMethod('POST', 'https://api.example.com/users', $data);
var_dump($response);

// PUT example
$data = array('email' => 'jane.new@example.com');
$response = callApiMethod('PUT', 'https://api.example.com/users/123', $data);
var_dump($response);

// DELETE example
$response = callApiMethod('DELETE', 'https://api.example.com/users/123');
var_dump($response);

Conclusion

This PHP helper function is ideal for any developer integrating external APIs. Customize headers, handle authentication, and scale easily. Explore further in the PHP cURL manual.

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.