Authentication in header with REST API - rest

I am new to coding and trying to work with my first API in Javascript. I am having some trouble figuring out where to populate an API key and header. It is a POST for sending a small message to an IOT device. The reference is here and the header reference is here.
Here is what I have, but I have replaced my API key with the generic one.
request.open('POST', 'https://dashboard.hologram.io/api/1/devices/messages');
request.setRequestHeader('Content-Type', 'application/json');
request.onreadystatechange = function () {
if (this.readyState === 4) {
console.log('Status:', this.status);
console.log('Headers:', this.getAllResponseHeaders());
console.log('Body:', this.responseText);
}
};
var body = {
'deviceid': [storedDeviceID],
'protocol': 'TCP',
'port': 80,
'data': 'Hello world!',
'base64data': 'SGVsbG8gd29ybGQhCg=='
};
request.send(JSON.stringify(body));
I really appreciate any help. Thank you.

Hologram provides an API Key which you need to encode in base64 format first then you can use it in your program.
So you can go to base64encode or any other conversion website ( you can encode it programmatically as well ) and there you have to enter -
apikey:YOUR_API_KEY
Then encode it into base64 format which will be something like
ABCDEFGHIJKLMNOpQrstUVW==
Copy it, and use it in your program. Below is an example using Javascript Fetch API -
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic ABCDEFGHIJKLMNOpQrstUVW==");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://dashboard.hologram.io/api/1/links/cellular", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));

Related

Issue with fetch PHP not getting POST data

I'm using the following code :-
Javascript :-
var t_sql="SELECT * FROM `compliance_report`;";
const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify( {sql: t_sql} )
};
fetch( 'test3.php', options )
.then( response => response.json() )
.then( response => {
console.log(response);
} );
The PHP code is just to echo back the Post data
:-
<?php
$sql=$_POST['sql'];
$au=json_encode($sql);
echo $au;
?>
But all I am getting back is NULL? can anyone tell me what is wrong. I ultimately want to run the query and echo back the result but the server is reporting the $_POST as empty?

REST call to Microsoft Graph

I have got my access token but I am struggling to see how you then send the request for the data required. In the example Call Microsoft Graph they have:
GET
https://graph.microsoft.com/v1.0/me/messages?$select=subject,from,receivedDateTime&$top=25&$orderby=receivedDateTime%20DESC
Accept: application/json Authorization: Bearer token
But what is the method for parsing the Accept: and the Authorization: to Microsoft Graph?
I have tried as a POST but it says bearer token empty.
$token=$_SESSION['$token'];
$url = 'https://graph.microsoft.com/v1.0/me/calendarview?startdatetime=2018-02-08T18:29:54.171Z&enddatetime=2018-02-15T18:29:54.171Z';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => array(
Authorization => 'Bearer ' . $token,
Content-Type => 'application/json'
)
)
);
$resp = curl_exec($curl);
curl_close($curl);
Use the provided graphServiceClient
// Create Microsoft Graph client.
try
{
graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
var token = await GetTokenForUserAsync();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
return graphClient;
}
Use that to authenticate your request.
$request = 'https://graph.microsoft.com/v1.0/me/calendarview?startdatetime=2018-02-08T18:29:54.171Z&enddatetime=2018-02-15T18:29:54.171Z';
hrm = new HttpRequestMessage(HttpMethod.Get, request);
// Authenticate (add access token) our HttpRequestMessage
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);
// Send the request and get the response.
response = await graphClient.HttpProvider.SendAsync(hrm);
jsonString = await response.Content.ReadAsStringAsync();

axios post server does not receive data from browser

I am using axios.post but the server does not seem to receive the post-data.
This is what I have:
var baseURL = "http://localhost:8888/dbRouting.php";
var body = {
function: 'foo',
id: 'bar',
}
axios.post(baseURL, body)
.then((response) => { console.log( "Data Loaded AXIOS: " + response.data ); })
.catch(function (error) {console.log(error);});
// Data Loaded AXIOS: array(0) {
// }
This jQuery post to the same file, on the other hand, works:
$.post( baseURL, body )
.done(function( data ) {
console.log( "Data Loaded JQUERY: " + data );
});
//Data Loaded JQUERY: array(2) {
//["function"]=>
//string(3) "foo"
//["id"]=>
//string(3) "bar"
//}
The server file (dbRouting.php) is just:
<?php
var_dump($_POST);
?>
Any ideas what might be going on?
This is my way of allowing the back-end which is php to process it via $_POST. This is part of my code in vue inside method section.
Assuming you are post it to a post_url and you have an object, var myObject:
var myObject = {
property: value,
property1: value1,
property2: value2
}
Inside my vue, method section:
updateForm: function( myObject ){
var post_url = (your post url);
axios.post(post_url, makePostReady( myObject ) )
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
Then above(before axios post call) or make it a global function. I created below function to turn any object I want to send as post using axios so that it will form
property=value&poperty1=value1&property2=value2......
Below is the function:
function makePostReady( object )
{
var sentence = "";
for (var key in object) {
sentenceAdd = key + '=' + object[key] + '&';
sentence = sentence + sentenceAdd;
}
//console.log( 'sentence: ' + sentence );
return sentence;
}
After that you can var_dump( $_POST ) at your post_url to check if everything is fine. Then you can process the data as usual.
Hopefully it helps
Below is some picture to help understanding better
It seems a networking issue.
Double check the URL and the port localhost:8888/dbRouting.php on JQuery & Axios demo
Are they exactly the same?
Is your .catch fired on axios? What's the error?
is your server responding on localhost:8888?
Alternatively, you can check your server implementation using a different client (e.g. Postman https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en)

Soundmanager2 Soundcloud API crossdomain.xml

I am using Soundmanager2 to stream files from soundcloud and display Eq visuals, but I'm having trouble with getting the eqdata when pausing or changing a track.
Shown here
I understand that Flash is unable to access the metadata due to the cross domain policy defined in the "crossdomain.xml" file on soundcloud as seen in this post: (and many others)
How to use SoundManager2 to stream from SoundCloud, and make visualizations?
I realize that I have to resolve the track's stream_url before loading it into sound manager. I'm doing this with an ajax call to a php script that resolves the url (shown below):
var client_id = '866143113772fec9556700f7f88f3abc',
url = 'http://api.soundcloud.com/resolve.json?url=http://soundcloud.com/aries-audio-music/tracks&client_id=';
$.getJSON(url+client_id+'&callback=?', function(playlist){
$.each(playlist, function(index, track) {
//append to playlist
$('<li id="tr-'+track.id+'">' + track.title + '</li>').data('track', track).appendTo('.tracks');
//get resolved stream url
$.ajax({
type: 'GET',
url: 'get_sc_url.php?id='+track.id,
success: function(data) {
console.log(data);
sm2_addtrack(track, data); //create SM2 sound object with resolved url
}
});
});
});
function sm2_addtrack(track, stream_url) {
soundManager.createSound({
id: 'track_' + track.id,
url: stream_url,
usePolicyFile : true,
usePeakData: false,
useWaveformData: false,
useEQData: true,
.....
get_sc_url.php used to resolve stream_url
<?php
require 'include/referrer_check.php';
require 'include/SC_API_KEY.php';
require 'include/API_cache.php';
$track_id = intval($_GET['id']);
$key = get_soundcloud_api_key();
$api_call = 'http://api.soundcloud.com/tracks/'.$track_id.'/stream/?client_id='.$key;
function get_web_page($url) {
/*
* hat tip: http://forums.devshed.com/php-development-5/curl-get-final-url-after-inital-url-redirects-544144.html
*/
$options = array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => false, // return web page
CURLOPT_HEADER => true,
CURLOPT_NOBODY => true,
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_RETURNTRANSFER => true, // return web page
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
return $header;
}
$myUrlInfo = get_web_page($api_call);
echo $myUrlInfo["url"];
?>
The result I am getting is something like this:
ec-media.soundcloud.com/Ez0B3lUZjjCR.128.mp3?f10880d39085a94a0418a7ef69b03d522cd6dfee9399eeb9a52200996dfabd3cefb29b7554ff4fd02baab5100d3a070e07d55f6e1eb41808c65398ce84cd496788c171f7e4&AWSAccessKeyId=AKIAJNIGGLK7XA7YZSNQ&Expires=1415223069&Signature=A0qaC1Nr3%2FXw4jwFYMjA%2F98arwI%3D
which plays but gives me no spectrum data at all and I still get the
computeSpectrum() (EQ data) SecurityError: Error #2123
from soundmanager2.
I know for sure that ec-media.soundcloud.com/crossdomain.xml is being downloaded, but I still can't solve this problem.
I think it may be because I'm trying to access the soundcloud crossdomain.xml policy file (which is HTTPS) from a HTTP document. secure="false" is not defined in Soundcloud's crossdomain.xml policy file so it defaults to secure="true", therefore the SWF can not access anything.
I doubt Soundcloud will ever set secure="false" in their crossdomain.xml for obvious reasons (it defeats the purpose of even having HTTPS).
I "think" this is why I get computeSpectrum() (EQ data) SecurityError: Error #2123, but I don't have access to a HTTPS enabled server to test this so I could be wrong.

Google Latitude and OAuth Signed requests

I've written a script that authenticates against Google's OAuth API for Latitude, using Net::OAuth. It correctly authenticates (as I can successfully fetch data out of the API). However, when I try to add an historical entry, I get a 401 Unknown authorization header response. I'm using the following code:
my $location_data = $json->encode(\%data);
$request = Net::OAuth->request("protected resource")->new(
consumer_key => $c_key,
consumer_secret => $c_secret,
token => $token,
token_secret => $token_secret,
verifier => $verifier,
request_url => 'https://www.googleapis.com/latitude/v1/location',
request_method => 'POST',
signature_method => $s_method,
timestamp => time,
nonce => &nonce(),
extra_params => {
key => $s_key
}
);
$request->sign;
$ua->default_header("Authorization", $request->to_authorization_header);
$ua->default_header("Content-Type", "application/json");
my $res = $ua->post('https://www.googleapis.com/latitude/v1/location?key=' . $s_key,
Content => $location_data);
All of the variables are used in the fetch portion of the API, so I know those are all ok. I'm not sure if I'm using the correct URL to post against, and I've tried what's in the sample above, as well as $request->to_url.
Any suggestions would be greatly appreciated.
After some back and forth with the Latitude API team, it was determined that this error comes from the fact that the Content-Type is not actually being set to application/json. Changing the above code to:
$ua->default_header("Authorization", $request->to_authorization_header);
my $res = $ua->post('https://www.googleapis.com/latitude/v1/location?key=' . $s_key,
'Content-Type' => 'application/json',
Content => $location_data);
And everything works as expected.