I am trying to connect to an API with Powershell using Invoke-RestMethod, but I keep running into an error for invalid credentials. I am converting the -Body to JSON in my API call. The documentation states there is no header and only 2 parameters: the username and password. I am also using -ContentType application/json, although I believe the issue lies with the JSON and not the Powershell itself.
The API has a test on their website where you can input your credentials to get an API key, which works fine so I know the credentials are correct. They also have a textbox to test authentication with JSON, which throws an error. The JSON I am testing looks like this:
{
"username": "myusername",
"password": "xxxxxxxx"
}
The API documentation also provides a sample PHP script to get an API key, which I confirmed does work when I put my credentials into it. The sample script is below:
$url = "https:website.com/api";
$content = ["username"=>"myusername","password"=>"********"];
$curl = curl_init($url);
if($curl) {
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// POST method
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($content));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = json_decode($json_response, true);
} else {
die("failed to connect\n");
}
I am not a PHP developer, but after looking up every command I believe I understand what it is doing for the most part. I am just wondering if I am missing anything in my JSON that the PHP script might add. In the PHP script I did convert the $content variable to JSON and it is identical to the JSON provided above, as well as the JSON used in the Powershell command.
As a side note, I have also tested it with with a SecureString in Powershell, which yielded the same results. Once I get the JSON to work I am planning on using a SecureString.
Any kind of assistance would be very helpful. Thank you!
Related
I am working with rest API. I am using zoho API's for making calls. Working in yii2 I am trying to call a GET API which gives me some details about my project.
/* Set the Request Url (without Parameters) here */
$request_url = 'https://projectsapi.zoho.com/restapi/portal/[PORTALID]/projects/[PROJECTID]/bugs/defaultfields/';
$ch = curl_init($request_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('authtoken' => 'key')); // here i am using key but in actual i am putting the real key value
$curl_response = curl_exec($ch);
$json = json_decode($curl_response);
var_dump($json);
exit();
Accessing it via POSTMAN when I run this call it gives me NULL in response. I have also tried out the way mentioned in the PHP Example here. But it doesn't work out for me as well.
I must be missing something that I don't know.
Any help would be highly appreciated.
Try checking your headers and make sure you're passing through all the required fields for an example authorization, content type etc.
New Twilio developer here. My app uses the IBM Watson Speech-to-text Add-on, but I'm having trouble accessing the results payload in my callback. I can't find helpful documentation or any discussion of the issue in forums.
What I know/What I've tried
The payload resource exists – I'm able to access it directly via browser.
Using the syntax prescribed by the Twilio PHP helper library client returns a 61005 "Bad request" error:
$request = $client->v1->lookups
->phoneNumbers("+1XXXXXXXXXX")
->fetch(
array(
"AddOns" => "ibm_watson_speechtotext",
));
Using cURL to get the resource directly has been equally unfruitful, returning an empty string.
$request = json_decode($_REQUEST['AddOns']);
error_log("URL: ".$request->results->ibm_watson_speechtotext->payload[0]->url);
$ch = curl_init($request->results->ibm_watson_speechtotext->payload[0]->url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$account_sid:$token");
$json = curl_exec($ch);
if($json === false) {
error_log("cURL error: ".curl_error($ch));
error_log(print_r($json,true));
}
curl_close($ch);
$obj = json_decode($json);
Any recommendations?
The following resources should help you find the results you're looking for.
Your first code snippet above doesn't apply (Lookup is a different product).
instead you will want to use the add-on results api to grab the results.
https://www.twilio.com/docs/api/add-ons/results-api
For your second snippet, you will need to enable follow redirect option with CURL.
Clients will need to follow the redirect to receive the data
associated with a Payload resource.
These may also help as you explore add-ons:
https://www.twilio.com/docs/api/add-ons/using-add-ons#add-on-results-available-callback
and
https://www.twilio.com/docs/guides/voice/how-to-use-recordings-add-ons-in-python
I have a cURL request in my code which works fine when running locally:
$url = "http://ipinfo.io/{$_SERVER['REMOTE_ADDR']}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$locale = json_decode($response);
and returns a JSON as expected. Our production system is on Google App Engine, however, where I get the website version for a browser rather than the JSON.
I can get this cURL request to work if I change
google_app_engine.enable_curl_lite = "1"
in the php.ini in the root directory of my project to
extension = "curl.so"
but Google's documentation insists the former is to be used on production. Additionally, using the latter breaks things like Monolog's SlackHandler.
Is there a way to get the JSON from this cURL request while still using Google's "cURL Lite"?
From the ipinfo.io documentation:
"We do a little bit of magic on the server to determine if we should send the JSON response or the webpage. We usually get it right, but if you're seeing the webpage instead of the JSON (or want to check the JSON output in a browser) you can force the JSON response by adding /json to the end of the URL"
Adding /json to the end of the URL worked for me in this case, but I wanted a more general solution. Since Google's cURL Lite uses their URL Fetch in the background, ipinfo.io's "magic" is somehow getting confused. I found that by specifying the Accept header then the /json addition wasn't required. In PHP:
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
Thanks to the folks on the #php channel of NashDev Slack for helping me on this one!
I got stuck while trying to set up cURL to retrieve data from other site(s)
Here is my situation.
I have 2 websites :
A
B
Website A sent data to website B as json format.
Of course, website A will have to encode all of it data before sending out - that's done.
Let the :
username = test
password = 1234
Website B just need run this command
curl --user test:1234 http://localhost/api/
They will then get the json file, and make anything out of it.
But, what if I have to do a mutiple cURL request.
SO I want to write a php script to do that.
This is what I have so far :
<?php
$ch = curl_init("http://localhost/api/");
$fp = fopen("api.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>
Questions
While doing it this way, I am not sure how to configure the username and password.
After, knowing where to set the username and password, where should I do the decoding of the json ?
After that, how do I display those data that I just decoded in a HTML/PHP format ?
How do I test it ?
Set the username and password
Website B is using HTTP Basic Authentication. This is a authentication method via HTTP headers. You'll have to set the username and password in the Authorization header. This can be done With the cUrl module for PHP like this:
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
Decode your result
Assuming you just need the JSON data that website B is returning. Use the following option. It will make curl_exec() return the HTTP body instead of outputting it directly.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
For the list of options that can be used with the PHP curl module check the documentation on curl_setopt(). Now you are ready to make your request with cUrl using curl_exec() like this:
$body = curl_exec($ch);
Then decode the JSON data, for the sake of simplicity lets decode it to a PHP array:
$data = json_decode($body, true);
Test your code
In my opinion PHP is not a language which offers great testing features. Putting that aside, most of the time I test my code in an interactive shell. To start testing your scenario in an interactive shell you should have PHP CLI installed on your system. In linux this is straight forward. Start an interactive PHP shell with the following command:
php -a
Now you can start putting together your scenario.
php > $ch = curl_init('http://echo.jsontest.com/key/value/one/two');
php > curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
php > $body = curl_exec($ch);
php > var_dump($body);
string(39) "{
"one": "two",
"key": "value"
}
"
php > $data = json_decode($body, true);
php > print_r($data);
Array
(
[one] => two
[key] => value
)
You can configure username and password like this
//cURL Options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => 'test:1234', // username:test pass:1234
CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options like this
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
How do you test it?
I would put all that in a .php file and call it on the browser to debug to keep it simple.
I am new to APIs and I am having trouble updating the status of issues. I have successfully listed projects and issues but not sure how to update them. I am using PHP to access the API. Can some one please share some example in php to how to update an issue using json. I have read the API documentation but its too minimal. I am not familiar with PUT and I cant find any good example or tutorial on the internet. Thankyou!
This what I tried but didnt work
function update_issue($issue_id){
// set url
$planio_url = "http://something.plan.io/issues/".issue_id.".json?key=185f1edsadfsdafy86578ce82ea70a0eb4267";
// create curl resource
$ch = curl_init();
$data = '{"issue":{"status":{"name":"done","id":21},"notes":"closing all old issues"}}';
$data = json_decode($data);
$ch = curl_init($planio_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if(!$response) {
return false;
}else{
return $response;
}
}
Returns empty response.
For everybody who wants to copy the snippet above. to update a ticket (like i did)
The URL in $planio_url is missing a $
..issues/".issue_id.".json
must be:
issues/".$issue_id.".json
also i decoded the json with true as second parameter to get an array for http_build_query
works like a charm.