How To make HTTP requests (PUT, POST, GET, DELETE) to APIs in PHP

To make HTTP requests (PUT, POST, GET, DELETE) to APIs in PHP using a function, you can create a versatile function that handles all types of requests. Here’s an example of how to do it:

 

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

 

Explanation:

  1. The callApiMethod() function uses cURL to interact with APIs. It accepts the URL of the API endpoint as the first parameter and allows you to specify the HTTP method (GET, POST, PUT, DELETE) using the $method parameter. It also allows you to set custom headers using the $headers parameter and send data as an array using the $data parameter.
  2. curl_init() initializes a cURL session.
  3. The cURL options are set using curl_setopt(). Here, we set the URL, return transfer as a string instead of directly outputting it, and set the custom request method (GET, POST, etc.).
  4. If headers are provided, they are set using CURLOPT_HTTPHEADER.
  5. If data is provided, it is sent as the request payload using CURLOPT_POSTFIELDS. The data is converted to a query string using http_build_query().
  6. curl_exec() executes the cURL request, and the response is stored in $response.
  7. We check for cURL errors using curl_errno(). If there is an error, the function returns an array with an error message.
  8. The cURL session is closed using curl_close().
  9. The function returns the API response after decoding it from JSON to a PHP array using json_decode().

Usage:

Here’s an example of how you can use the callApiMethod() function to make API requests:

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

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

 

Leave a Comment

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