2

I am able to do the HTTP GET request using cURL in my custom function, my code below works fine for me, but is there Drupal way to do this?

function some_page_callback() {
    $url = 'https://api.example.com/data';
    $accesstoken = 'SoMedGFidHThX2NvdW50eV90bWNhOkEyakJEM2ND';
    $headr = array();
    $headr[] = 'Accept: application/json';
    $headr[] = 'Authorization: Basic '.$accesstoken;

    //cURL starts
    $crl = curl_init();
    curl_setopt($crl, CURLOPT_URL, $url);
    curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
    curl_setopt($crl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($crl, CURLOPT_HTTPGET,true);
    $reply = curl_exec($crl);

    //error handling for cURL
    if ($reply === false) {
       // throw new Exception('Curl error: ' . curl_error($crl));
       print_r('Curl error: ' . curl_error($crl));
    }
    curl_close($crl);
    //cURL ends

    //decoding the json data
    $decoded_data = json_decode($reply, true);


    // putting the data into table 
      $rows = array();

      $output = '';
      // Example of theme_table().
      $output .= '<h2>Example</h2>';
      $headers = array(t('ID'), t('Name'));

      foreach ($decoded_data['data'] as $line) {
          $tablerow = array(
          array('data' => $line['id']),
          array('data' => $line['name']),
         );
          $rows[] = $tablerow;
      }
      $output .= theme('table', array('header' => $headers, 'rows' => $rows));

return $output;
}

2 Answers 2

2

I ended up needing to do something like this not too long ago in a custom module. Drupal has a function called drupal_http_request() to hit the external URL. You can execute it inside a hook function if necessary in your module.

$url = 'http://my-url.com';
      $response = drupal_http_request($url);
2
  • I tried this function, but I am not able to put Authentication field in header, how do I do that? Thank you.
    – shrish
    Feb 2, 2014 at 5:36
  • 1
    @shrish I can't provide you with specifics on your exact implementation, but the docs list headers as an available parameter. function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3, $timeout = 30.0) {
    – Jon Girard
    Feb 2, 2014 at 5:50
1

The equivalent in Drupal 8 would be the Guzzle HttpClient as documented by this change record

try {
  $response = \Drupal::httpClient()->request('GET', $url);
  $data = $response->getBody()->getContents();

  //if dealing with json file
  $decoded = json_decode($data);
  if (!$decoded) {
    throw new \Exception('Invalid data returned from API');
  }

} catch (\Exception $e) {
  return "";
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.