Skip to content

Instantly share code, notes, and snippets.

@dyazincahya
Last active February 11, 2024 08:21
Show Gist options
  • Save dyazincahya/dc6c947a984794db35e45f0a2aed35ea to your computer and use it in GitHub Desktop.
Save dyazincahya/dc6c947a984794db35e45f0a2aed35ea to your computer and use it in GitHub Desktop.
Simple Helper cURL PHP for access API with method GET POST PUT and DELETE
<?php
function makeApiRequest($url, $params = [], $method = 'GET') {
// Initialize cURL session
$ch = curl_init($url);
// Set common cURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string instead of outputting it
// Set method-specific cURL options
if ($method === 'POST') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
} elseif ($method === 'PUT') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
} elseif ($method === 'DELETE') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
} elseif ($method === 'GET') {
// Append parameters to the URL for GET requests
if (!empty($params)) {
$url .= '?' . http_build_query($params);
}
}
// Execute cURL session and get the response
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
echo 'Curl error: ' . curl_error($ch);
}
// Close cURL session
curl_close($ch);
// Return the API response
return $response;
}
?>
@dyazincahya
Copy link
Author

how to usage?

<?php 

  // Example usage for GET request
  $name = 'kim';
  $countryId = 'US';
  $api_url_get = 'https://api.example.io';
  $params_get = [
      'name' => $name,
      'country_id' => $countryId,
  ];

  $responseGet = makeApiRequest($api_url_get, $params_get, 'GET');
  echo "GET Response: $responseGet\n";


  // Example usage for POST request
  $api_url_post = 'https://api.example.com/posts';
  $params_post = [
      'title' => 'New Post',
      'content' => 'This is the content of the new post.',
  ];

  $responsePost = makeApiRequest($api_url_post, $params_post, 'POST');
  echo "POST Response: $responsePost\n";


  // Example usage for PUT request
  $api_url_put = 'https://api.example.com/123';
  $params_put = [
      'title' => 'Updated Post',
      'content' => 'This is the updated content of the post.',
  ];

  $responsePut = makeApiRequest($api_url_put, $params_put, 'PUT');
  echo "PUT Response: $responsePut\n";


  // Example usage for DELETE request
  $api_url_delete = 'https://api.example.com/123';
  $responseDelete = makeApiRequest($api_url_delete, [], 'DELETE');
  echo "DELETE Response: $responseDelete\n";

?>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment