How to set multiple header value in Slim Framework 3 to a web service with api key?

1k views Asked by At

I'm new in Slim Framework 3. I have a problem to accessing web service that has a Api Key header value. I have had a Api Key value and wanna access the web service to get JSON data. Here is my slim get method code:

$app->get('/getbooking/{id}', function (Request $request, Response $response, $args) {
  $id = $args['id'];
  $string = file_get_contents('http://maindomain.com/webapi/user/'.$id);


  //Still confuse how to set header value to access the web service with Api Key in the header included.
});

I have tried the web service in Postman (chrome app) to access and I get the result. I use GET method and set Headers value for Api Key.

But how to set Headers value in Slim 3 to get access the web service?

Thanks for advance :)

1

There are 1 answers

0
Rob Allen On

This doesn't actually have anything to do with Slim. There are multiple ways to make an HTTP request from within PHP including streams (file_get_contents()), curl and libraries such as Guzzle.

Your example uses file_get_contents(), so to set a header there, you need to create a context. Something like this:

$app->get('/getbooking/{id}', function (Request $request, Response $response, $args) {
  $id = $args['id'];  // validate $id here before using it!

  // add headers. Each one is separated by "\r\n"
  $options['http']['header'] = 'Authorization: Bearer {token here}';
  $options['http']['header'] .= "\r\nAccept: application/json";

  // create context
  $context = stream_context_create($options);

  // make API request
  $string = file_get_contents('http://maindomain.com/webapi/user/'.$id, 0, $context);
  if (false === $string) {
    throw new \Exception('Unable to connect');
  }

  // get the status code
  $status = null;
  if (preg_match('@HTTP/[0-9\.]+\s+([0-9]+)@', $http_response_header[0], $matches)) {
      $status = (int)$matches[1];
  }

  // check status code and process $string here
}