How to send http header with data to rest Api codiegniter? - php

I want to send http header to Api and get json response.
I have all book detail in books table and I want to get all books.
But i have 5 http header to get access them.
Client-Service,Auth-Key,Content-Type,User-ID,Authorization
Url to get details:
http://127.0.0.1/RestApi/index.php/book/
Controller Code:
public function index() {
$method = $_SERVER['REQUEST_METHOD'];
if ($method != 'GET') {
json_output(400, array('status' => 400, 'message' => 'Bad request.'));
} else {
$check_auth_client = $this->MyModel->check_auth_client();
if ($check_auth_client == true) {
$response = $this->MyModel->auth();
if ($response['status'] == 200) {
$resp = $this->MyModel->book_all_data();
json_output($response['status'], $resp);
}
}
}
}
Model Code:
public function book_all_data()
{
return $this->db->select('id,title,author')->from('books')->order_by('id','desc')->get()->result();
}
I want to access to access on button click but how send http header to rest api page and get all data using codeigniter ?

Use CURL to set headers. See below example. Hope it will help you
$headers = array(
'Client-Service:CLIENT_SERVICE_DETAIL',
'Auth-Key:YOUR_AUTH_KEY',
'Content-Type:YOUR_CONTENT_TYPE',
'User-ID:YOUR_USER_ID',
'Authorization:YOUR_AUTHORIZATION',
);
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, YOUR_URL);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_HEADER, 1);
curl_setopt($curl_handle, CURLOPT_HTTPHEADER, $headers);
$buffer = curl_exec($curl_handle);
$header_size = curl_getinfo($curl_handle, CURLINFO_HEADER_SIZE);
$body = substr($buffer, $header_size);
curl_close($curl_handle);

Related

Translation On Telegram Bot

if (strpos($message, "/translate") === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
file_get_contents($apiURL."/sendmessage?chat_id=".$chatID."&text=Hasil translate: ".$word." : $mymemori ");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_string);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(($html = curl_exec($ch)) === false) {
echo 'Curl error: ' . curl_error($ch);
die('111');
}
}
Hello guys i was trying to make translation bot on telegram using php but the output is still error or no output at all. Am using this API https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|id
Please help how to get the translation
Error output IMAGES
First, I suggest using cURL, Not file_get_contents.
Second, No need to echo anything, Because the URL will be visited by webhook, Not a human.
Third, You need a method to send requests to Telegram Bot API.
Use this new code:
define('Token', '<your_bot_token>');
# Reading the update from Telegram
$update = json_decode(file_get_contents('php://input'));
$message = $update->message;
$text = $message->text;
if (strpos($text, '/translate') === 0) {
$word = substr ($message, 10);
$mymemori = json_decode(file_get_contents("https://api.mymemory.translated.net/get?q=".$word."&langpair=en|id"), TRUE)["matches"]["translation"];
//
Bot('sendMessage', [
'chat_id' => $update->message->chat->id,
'text' => "Hasil translate: $word : $mymemori "
]);
}
function Bot(string $method, array $params = [])
{
$ch = curl_init();
$api_url = 'https://api.telegram.org/bot' . Token . "/$method";
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$result = curl_exec($ch);
if ($result->ok == false)
{
throw new Exception($result->description, $result->error_code);
}
return $result->result;
}

Shopify REST API Pagination Link Empty

Situation
I am trying to make a call to the Shopify REST API where I have more than 50-250 results but I am not able to get the Link Header from the cURL Response which contains the Pagination Links.
Sample of Link Headers from the API Documentation for Cursor-Pagination (https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api)
#...
Link: "<https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={next}, <https://{shop}.myshopify.com/admin/api/{version}/products.json?page_info={page_info}&limit={limit}>; rel={previous}"
#...
The link rel parameter does show up, but the Link is empty as below.
My Shopify Call function
function shopify_call($token, $shop, $api_endpoint, $query = array(), $method = 'GET', $request_headers = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . $api_endpoint;
if (!is_null($query) && in_array($method, array('GET', 'DELETE'))) $url = $url . "?" . http_build_query($query);
$headers = [];
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
// this function is called by curl for each header received
curl_setopt($curl, CURLOPT_HEADERFUNCTION,
function($ch, $header) use (&$headers)
{
$len = strlen($header);
$header = explode(':', $header, 2);
if (count($header) < 2) // ignore invalid headers
return $len;
$headers[trim($header[0])] = trim($header[1]);
return $len;
}
);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'Sphyx App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl,CURLOPT_ENCODING,'');
// Setup headers
$request_headers[] = "";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
$request_headers[] = 'Accept: */*'; // Copied from POSTMAN
$request_headers[] = 'Accept-Encoding: gzip, deflate, br'; // Copied from POSTMAN
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
if ($method !== 'GET' && in_array($method, array('POST', 'PUT'))) {
if (is_array($query)) $query = http_build_query($query);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $query);
}
// Send request to Shopify and capture any errors
$result = curl_exec($curl);
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $result, 2);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => json_decode($response[1],true));
}
}
But when I use a POSTMAN Collection, I get a proper formatted response without the Link getting truncated/processed.
I have tried a lot of things here available via the StackOverflow Forums as well as Shopify Community, but I'm unable to parse the Response Header the same way as shown by API Examples or POSTMAN
My issue does seem to be with the PHP Code, but I'm not a pro with cURL. Thus, I'm not able to make it further :(
Also, I'm not able to understand why POSTMAN's Headers are in Proper Case whereas mine are in Lower Case
Thanks in Advance!
Found my answer :
https://community.shopify.com/c/Shopify-APIs-SDKs/Help-with-cursor-based-paging/m-p/579640#M38946
I was using a browser to view my log files. So the data is there but it's hidden because of your use of '<'s around the data. I had to use the browser inspector to see the data. Not sure who decided this syntax was a good idea. Preference would be two headers that one can see and more easily parse since using link syntax is not relative to using an API.
My suggestion would be 2 headers:
X-Shopify-Page-Next: page_info_value (empty if no more pages)
X-Shopify-Page-Perv: page_info_value (empty on first page or if there is no previous page).
Easy to parse and use.
But having this buried as an invalid xml tag, having them both in the same header and using 'rel=' syntax makes no sense at all from an API perspective.

How can I get an Authentication Token for Microsoft Translator API?

I want to get an Authentication Token for the Microsoft Translator API. This is my code:
<?php
//1. initialize cURL
$ch = curl_init();
//2. set options
//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);
// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');
//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);
//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));
//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);
if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}
//4. close and free up the curl handle
curl_close($ch);
//5. display raw output
print_r($output);
?>
it gives me the following error:
{ "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }
which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.
http://docs.microsofttranslator.com/oauth-token.html
I did find some examples online on how to get the Authenticationtoken, but they are outdated.
How can I get the AuthenticationToken/achieve that microsoft recognises my key?
You're passing the subscription-key wrong -
The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=
And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.
FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose:
http://docs.microsofttranslator.com/oauth-token.html
Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):
<?php
define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");
class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}
class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;
private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}
function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);
$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}
}
function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}
echo bing_translator("How about translating this?");
?>
Add your key also in the URL.
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');
But leave it also in the CURLOPT_POSTFIELDS.

CURL gives 500 Internal server error

I am unable to make the API call using CURL. Below is the code for making the API call using CURL
$ch=curl_init("http://sms.geekapplications.com/api/balance.php?authkey=2011AQTvWQjrcB56d9b03d&type=4");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array("Authorization: Bearer"));
// execute the api call
$result = curl_exec($ch);
echo ($result);
First you might wanna be using a function for this.. and your CURL it not build correctly. Please see my example
//gets geekapplications SMS balance
function getBalance() {
$url = 'http://sms.geekapplications.com/api/balance.php?' . http_build_query([
'authkey' => '2011AQTvWQjrcB56d9b03d',
'type' => '4'
]);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http == 200) {
$json = #json_decode($response, TRUE);
return $json;
} else {
echo 'There was a problem fetching your balance...';
}
}
Use it within your controller try print_r($this->getBalance()); should output an array with your balance.

Wunderlist Tasks - how do I get the tasks for a list using curl in php

I have been searching quite a bit now and can't get an overview of Tasks from a single list using the Wunderlist endpoint: https://a.wunderlist.com/api/v1/tasks
I can get Lists, Folders and create List, Folders, Tasks so that works fine. But how do I get the Tasks from a list? I tried to interpret the documentation found here: https://developer.wunderlist.com/documentation/endpoints/task
When I do a GET method I get this error message:
{"error":{"type":"missing_parameter","translation_key":"api_error_missing_params","message":"Missing parameter.","title":["required"]}}
However, I don't want to add a title, since I don't want to create a new task, I just want the tasks of that list back.
What am I doing wrong here?
Here is my code so far:
function doCall($endPoint, $parameters = array(), $method = 'GET')
{
// check if curl is available
if (!function_exists('curl_init')) {
print "This method requires cURL (http://php.net/curl), it seems like the extension isn't installed. ".__LINE__;
exit();
}
//prepare content
$parametersdata = json_encode($parameters);
// define url
$url = 'https://a.wunderlist.com/api/v1/' . $endPoint;
// init curl
$curl = curl_init();
// set options
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
// init headers
$headers = array();
// add to header
$headers[] = 'X-Access-Token: XXX';
$headers[] = 'X-Client-ID: XXX';
// method is POST, used for login or inserts
if ($method == 'POST') {
// define post method
curl_setopt($curl, CURLOPT_POST, 1);
// method is DELETE
} elseif ($method == 'DELETE') {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
} else {
curl_setopt($curl, CURLOPT_HTTPGET, 1);
}
// parameters are set
if (!empty($parameters)) {
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-Length: ' . strlen($parametersdata);
curl_setopt($curl, CURLOPT_POSTFIELDS, $parametersdata );
}
// define headers with the request
if (!empty($headers)) {
// add headers
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
}
// execute
$response = curl_exec($curl);
// debug is on
if (true) {
echo $method." ".$url . '<br/><pre>';
print"\n--headers--\n";
print_r($headers);
print"\n--parameters--\n";
print_r($parameters);
print"\n--parametersdata--\n";
print_r($parametersdata);
print"\n--response--\n";
print_r($response);
echo '</pre><br/><br/>';
}
// get HTTP response code
$httpCode = (int) curl_getinfo($curl, CURLINFO_HTTP_CODE);
// close
curl_close($curl);
// response is empty or false
if (empty($response)) {
//throw new Exception('Error: ' . $response);
print "Error: ". $response." ".__LINE__;
}
// init result
$result = false;
// successfull response
if (($httpCode == 200) || ($httpCode == 201)) {
$result = json_decode($response, true);
}
// return
return $result;
}
$listid = 123;
$url = 'tasks';
$tasks = doCall($url,array('list_id' => $listid), 'GET');
echo $tasks;
-- EDIT ADDENDUM ---
I have also tried these variants in case anyone wonders. They all give the same error "bad_request"
GET a.wunderlist.com/api/v1/tasks{"list_id":"141329591"}
GET a.wunderlist.com/api/v1/tasks{"list_id":141329591}
GET a.wunderlist.com/api/v1/tasks/{"list_id":"141329591"}
As pointed out by Rotem, you're using adding the $parameters array as CURLOPT_POSTFIELDS. As the name suggests this is meant for http POST requests only.
Putting the parameters as query params in the $url and passing null for the query params made your example work for me.
$listid = 123;
$url = 'tasks?list_id=123';
$tasks = doCall($url,null,'GET');
echo $tasks;
Note: I did use a list_id I have access to instead of using 123

Categories