Send GET, POST, PUT, DELETE API Requests with PHP cURL

API API Integration Code Snippets Coding Blog Custom Code Snippets PHP Development Wordpress WordPress Development WordPress Hacks

Send GET, POST, PUT, DELETE API Requests with PHP cURL Tutorial/Guide

Interacting with APIs is a common task in PHP development. Whether you're fetching data or sending updates, this guide walks through handling GET, POST, PUT, and DELETE requests using a flexible function with cURL.

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;
}

How It Works

  1. callApiMethod() acts as a universal function to perform API operations based on the method provided.
  2. It initializes cURL, sets the correct method, and appends query strings or request bodies as needed.
  3. The curl_exec() function handles the actual request and returns the response.
  4. Error handling is built-in to catch failed connections.

Practical Example

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

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

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

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

Final Thoughts

This reusable PHP function simplifies how you interact with any RESTful API. By adjusting the HTTP method and parameters, you can manage data with ease. Want to explore more options? Visit the PHP cURL documentation.  

💡 Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.