Slim framework - Call external API - api

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);

Related

Executing a cURL request to an background remover API from PHP throws file not found error

I am new to cURL from PHP. I am trying to send file URL as post field and API Key as header to the background remover API to retrieve the background removed image. The error says:
{"errors":[{"title":"No image given","code":"missing_source","detail":"Please provide the source image in the image_url, image_file or image_file_b64 parameter."}]}
My code:
<?php
$url='https://api.remove.bg/v1.0/removebg';
$ch = curl_init($url);
$data = array('image_url'=> 'https://www.requestingservicebyme.com/upload/imageexample.jpg');
$headers1=['X-API-Key:xxxxxxxxxxxxxxx',
'Content-Type:application/json'];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$buffer = curl_exec($ch);
if (empty($buffer)) {
echo " buffer is empty ";
} else{
echo $buffer;
}
curl_close($ch);
?>
I was also working on it using the curl I got success in that ..!
Change your headers
Remove the application type json from headers as this api returns the data in Image content format.
$x = curl_init();
$headers=['X-API-Key:xxxxxxxxxxxxxxxxx'];
$data = array (
'image_url' => "https://amblin.com/wp-content/uploads/2019/09/castaway_2000_photo_29.jpg",
'size' => "auto",
);
$url = 'https://api.remove.bg/v1.0/removebg';
// $post = http_build_query($data);
$x = curl_init($url);
curl_setopt($x, CURLOPT_POST, true);
curl_setopt($x, CURLOPT_RETURNTRANSFER, true);
curl_setopt($x, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($x, CURLOPT_HTTPHEADER, $headers);
curl_setopt($x, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($x, CURLOPT_POSTFIELDS, $data);
$y = curl_exec($x);
curl_close($x);
//And then save it using this code
$fp = fopen("result.jpg", "wb");
fwrite($fp, $y);
fclose($fp);

How to create a table from this ForEach Loop?

I am trying to fetch all the domains I have purchased from Godaddy account using their API. However, It's not showing in a table format for proper view. Can anybody guide me on how to create a table out of this API results? Currently, it's showing results each at a different line but I prefer to view them in a table format.
Thanks!!
<?php
$domains = getDomains();
// check if error code
if(isset($domains['code'])){
$msg = explode(":",$domains['message']);
$msg = '<h2 style="text-align:center;">'.$msg[0].'</h2>';
// proceed if no error
} else {
$msg = '';
foreach ($domains as $domain){
$msg .= $domain['domain'].'</br>';
$msg .= $domain['createdAt'].'<br>';
$domain['createdAt'];
$domain['domain'];
$domain['domainId'];
$domain['expirationProtected'];
$domain['expires'];
$domain['holdRegistrar'];
$domain['locked'];
$domain['nameServers'];
$domain['privacy'];
$domain['renewAuto'];
$domain['renewDeadline'];
$domain['renewable'];
$domain['status'];
$domain['transferProtected'];
}
}
echo $msg;
function getDomains(){
$status = 'ACTIVE';
$limit = '999';
$url = "https://api.godaddy.com/v1/domains?statuses=$status&limit=$limit";
// set your key and secret
$header = array(
'Authorization: #########'
);
//open connection
$ch = curl_init();
$timeout=60;
//set the url and other options for curl
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET'); // Values: GET, POST, PUT, DELETE, PATCH, UPDATE
//curl_setopt($ch, CURLOPT_POSTFIELDS, $variable);
//curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
//execute call and return response data.
$result = curl_exec($ch);
//close curl connection
curl_close($ch);
// decode the json response
$dn = json_decode($result, true);
return $dn;
}
?>

Find out URL response to check broken Url's in Codeception

I have fetched multiple URL's using grabMultiple() method.
I want to check its response to check whether it is broken(i.e.404) or not.
Can I use HTTP Response in Codeception ? If yes what is the syntax ?
Use seeResponseCodeIs method.
$links = $I->grabMultiple('div.test-info a', 'href');
foreach ($links as $link) {
$I->amOnPage($link);
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
}
This worked for me -
function check_url($link){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $link);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10); //follow up to 10 redirections - avoids loops
$data = curl_exec($ch);
curl_close($ch);
preg_match_all("/HTTP\/1\.[1|0]\s(\d{3})/",$data,$matches);
$code = end($matches[1]);
if($code==404)
{
echo "Bad url";
}
else{
echo "Good url";
}
}

auto login for skydrive api php

I want to make just offline authentication in SkyDrive api PHP,just want to provide client_id,client_secret_key and access or refresh token which may be preferable and than authenticate me on that basis.After successful offline login create one folder in SkyDrive (OneDrive) and upload files inside that created folder.
And how to refresh access token automatically without login.
Please help me out if anyone have idea regarding that.
Finally i got it,
Please use the Following source it's work for me
https://github.com/lovattj/php-skydrive
Within that Below File is so useful
https://github.com/lovattj/php-skydrive/blob/master/src/functions.inc.php
i changed in curl function and it's work for me
For e.g
i replaced curl_get function by below and it work for me
protected function curl_get($uri, $json_decode_output="true", $expected_status_code="HTTP/1.1 200 OK") {
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri);
//curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
//curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
} catch (Exception $e){}
if ($httpcode == "201" || $httpcode == "200") {
return json_decode($result, true);
} else {
return array('error' => 'HTTP status code not expected - got ', 'description' => $httpcode);
}
var_dump(json_decode($result));
}

shorte.st new api convert to php curl

shorte.st is a url shorten service.
recently they changed the api as following:
curl commandline
curl H "public-api-token: fakekey" -X -d "urlToShorten=google.com" PUT http://api.shorte.st/v1/data/url
response:
{"status":"ok","shortenedUrl":"http:\/\/sh.st\/XXXX"}
How to change it into php curl version?
function shst($url){
$apiurl="https://api.shorte.st/v1/data/url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('public-api-token: fakekey','X-HTTP-Method-Override: PUT'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "urlToShorten=".$url);
$data = curl_exec($ch);
curl_close($ch);
$obj = json_decode($data);
$ret=$obj->{'shortenedUrl'};
return $ret;
}
The sample they provided used the wrong url. should be https not http
This works:
function shst($url){
$key="";//your key
$curl_url = "https://api.shorte.st/s/".$key."/".$url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curl_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$array = json_decode($result);
$shortest = $array->shortenedUrl;
return $shortest;
}