Jake Wilson
Jake Wilson

Reputation: 91193

How to pass custom header to RESTful call?

There are some web service APIs that I need to connect to for my website. Most of the APIs involve something like this:

$data = file_get_contents("http://www.someservice.com/api/fetch?key=1234567890

But one web service requires the API key to be set in a custom HTTP header. How do I make the request to this API url and pass the custom header at the same time?

Upvotes: 3

Views: 15653

Answers (4)

Shahzeb Naqvi
Shahzeb Naqvi

Reputation: 410

$headers = array(
   "Accept: application/json",
   "Content-Type: application/json",
   "Authorization: 42|W3hpHwxdYXSgOVRDsi7AD8Wg4pEKHebBey0AWpzH"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

Upvotes: 0

Jasper van den Bosch
Jasper van den Bosch

Reputation: 3218

$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'CUSTOM HEADER HERE',
)
));

$result = file_get_contents($url, false, $context);

Upvotes: 0

Rob
Rob

Reputation: 12872

You could use curl. For example:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.someservice.com/api/fetch?key=1234567890');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Header: value'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
curl_close($ch);

Upvotes: 4

stewe
stewe

Reputation: 42642

You could use stream_context_create like this:

<?php
$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"CustomHeader: yay\r\n" .
              "AnotherHeader: test\r\n"
  )
);
$context=stream_context_create($options);
$data=file_get_contents('http://www.someservice.com/api/fetch?key=1234567890',false,$context);
?>

Upvotes: 11

Related Questions