Drupal Answers is a question and answer site for Drupal developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 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;
share|improve this question
up vote 2 down vote accepted

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);
share|improve this answer
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 '14 at 5:36
@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 '14 at 5:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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