How to Make API Requests (PUT, POST, GET, DELETE) in PHP

How to Make API Requests (PUT, POST, GET, DELETE) in PHP

 

Making HTTP requests to APIs is a common task when working with external services in PHP. You can handle different request types such as GET, POST, PUT, and DELETE using a flexible function with cURL. Below is an example that demonstrates how to create such a function for all these HTTP methods.

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. callApiMethod() is a versatile function using cURL to handle different HTTP methods. The $method parameter allows specifying the HTTP method, such as GET, POST, PUT, or DELETE.
  2. curl_init() initializes a new cURL session for the given URL.
  3. For POST and PUT requests, the CURLOPT_POST and CURLOPT_CUSTOMREQUEST options are used, respectively, to indicate the method being used.
  4. If data is supplied, it is sent as the body of the request using CURLOPT_POSTFIELDS.
  5. The curl_exec() function sends the request, and the response is returned.
  6. If any errors occur during the cURL execution, the function will terminate and display an error message.
  7. The function returns the API response or a failure message in case of an error.

Usage Example

Here’s how to use the callApiMethod() function to make requests to an API.

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

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

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

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

Conclusion

This function allows you to perform all essential HTTP requests to APIs using PHP’s cURL extension. Customize it further by adding headers or modifying how data is sent to suit your needs. This simple yet versatile approach ensures that you can interact with any API smoothly from your PHP applications.

For more detailed cURL options, refer to the PHP cURL Documentation.

 

Related Blogs

Add same product to cart twice instead of changing quantity in Cart

By default, WooCommerce allows customers to change the quantity of a product in the cart by updating the quantity input field on the cart page. If the quantity is increased, the product will be added to the cart only once with the updated quantity. However, if you want to allow customers to add the same product multiple times as separate items in the cart, you’ll need to customize the cart behavior.

Elementor shortcodes

Elementor is a popular page builder plugin for WordPress that allows you to create and customize web pages using a drag-and-drop interface. Elementor provides a wide range of built-in widgets and elements, and you can also create your own custom elements using shortcodes.

Request A Quote

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.