I'm completely new to Slim Framework 2 and I would like to make an HTTP call to an external API.
It would simply something like:
GET http://website.com/method
Is there a way to do this using Slim or do I have to use curl for PHP?
You can build an API using Slim Framework. To consume other API, you can use PHP Curl.
So for example:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://website.com/method");
curl_setopt($ch, CURLOPT_HEADER, 0); // No header in the result
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return, do not echo result
// Fetch and return content, save it.
$raw_data = curl_exec($ch);
curl_close($ch);
// If the API is JSON, use json_decode.
$data = json_decode($raw_data);
var_dump($data);
?>
<?php
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://website.com/method");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TCP_KEEPALIVE, 1);
curl_setopt($ch, CURLOPT_TCP_KEEPIDLE, 2);
$data = curl_exec($ch);
if(curl_errno($ch)){
throw new Exception(curl_error($ch));
}
curl_close($ch);
$data = json_decode($data);
var_dump($data);
} catch(Exception $e) {
// do something on exception
}
?>
I prefer using file_get_contents which is able to fetch remote files and can be tuned using the $context
argument. The fourth example shows a get request.
$file = file_get_contents('http://www.example.com/', false, $context);