Error 400 : Required parameter part - javascript

Iam trying to use youtube api for finding the information about a particular video using youtube api.I have used the https module for sending and receiving data
This is the code I have used
var youtube_query=querystring.stringify({
q:'bangarang',
key:'api_key',
part:'snippet'
});
var options_you = {
host:'www.googleapis.com',
method:'GET',
path:'/youtube/v3/search'
};
function getvid_id(vid_result){
//callback function for finding the information on the video
vid_result.setEncoding('utf8');
console.log("STATUS :"+vid_result.statusCode);//to show the status code
vid_result.on('data', function (body) {
console.log(body);
});
}
var youtube_request = https.request(options_you,getvid_id);
youtube_request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
youtube_request.write(youtube_query);
youtube_request.end();
However I get the following response
STATUS :400
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required parameter: part",
"locationType": "parameter",
"location": "part"
}
],
"code": 400,
"message": "Required parameter: part"
}
}
As you can see ,I have already provided the part parameter.But I cannot find the reason why it is not working .

You can pass querystring directly to the path field as :
var querystring = require("querystring");
var https = require("https");
var youtube_query = querystring.stringify({
q: 'bangarang',
key: 'api_key',
part: 'snippet'
});
var options_you = {
host: 'www.googleapis.com',
method: 'GET',
path: '/youtube/v3/search?' + youtube_query
};
var youtube_request = https.request(options_you, function(res) {
res.on('data', function(d) {
process.stdout.write(d);
});
});
youtube_request.end();

Related

Upload to vimeo with tus-js-client

I’m new to tus and I’m using tus-js-client. I’m following the example in this link https://github.com/tus/tus-js-client/blob/master/docs/usage.md#example-upload-to-vimeo.
I was able to successfully upload a video on Vimeo but I would like to set the title/name and description in advance. And also the optional onSuccess function is not returning anything. I would like to get the video details that I’ve uploaded successfully like the clipid.
Are these things something possible to do on tus-js-client? Below is my code for reference.
function UploadVideoTusJs(uploadUrl, videoFile) {
var upload = new tus.Upload(videoFile.files[0], {
uploadUrl: uploadUrl,
metadata: {
name: videoFile.files[0].name, // not working
description: "Test", // not working
},
onError: function (error) {
console.log("Failed because: " + error);
},
onProgress: function (bytesUploaded, bytesTotal) {
var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2)
console.log(bytesUploaded, bytesTotal, percentage + "%")
},
onSuccess: function (data) {
console.log(data); //returns undefined
console.log("Download %s from %s", upload.file.name, upload.url);
},
onAfterResponse: function (req, res) {
var url = req.getURL()
var value = res.getHeader("X-My-Header")
console.log(`Request for ${url} responded with ${value}`)
}
});
// Start the upload by default
upload.start();
}
-- Dan
Vimeo's implementation of tus is a bit different as the "creation" step is done using the Vimeo API, not using tus. If you want to provide metadata like name or description, that should be provided with the initial API request, which should look something like this:
var settings = {
"url": "https://api.vimeo.com/me/videos",
"method": "POST",
"timeout": 0,
"headers": {
"Accept": "application/vnd.vimeo.*+json;version=3.4",
"Content-Type": "application/json",
"Authorization": "Bearer TOKEN"
},
"data": JSON.stringify({"upload":{"approach":"tus","size":666666666},"name":"name","description":"description"}),
};
$.ajax(settings).done(function (response) {
console.log(response);
});
Hope this points you in the right direction!

Try to execute js script in manifest to ask privatte API with post request

I try to use js script in my jps to test credentials with a personal APi. The idea is to return an error code in the jps if credentials are false. In my computer my js script works fine but when i try to start my jps with this i have an javascript error.
my jps:
onInstall:
- script [*]: https://github.com/user/project/blob/master/script.js
responses:
401:
type: error
message: bad credentials
My js script:
const https = require('https')
var name = "some-name"
var password = "some-password"```
const data = JSON.stringify({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
})
const options = {
hostname: 'mYapi.com',
port: 443,
path: 'mypath',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
}
var req = https.request(options, (res) => {
console.log(`statusCode: ${res.statusCode}`)
console.log(res.statusCode)
return res.statusCode;
})
req.on('error', (error) => {
console.error(error)
})
req.write(data)
req.end()
I get this error in the console :
ERROR: script.response: {"result":1704,"line":50,"response":null,"source":"hx-core","time":122,"error":"org.mozilla.javascript.EvaluatorException: syntax error"}
And i try a lot of differents script to do this post request ----> works in my computer ( api send result 201 if credentials are good and 401 if not ) , -----> doesn't work in jelastic manifest.
So please can you explain me how i can do a post request with json on my API in Jelastic manifest ( js call script ). I thank you in advance !
The code that is executed by the "script" action runs on the JVM therefore it allows you to connect and use Java libraries.
To implement a POST request and determine the status of the output code, you can use Commons HttpClient.
See below for an example.
type: install
name: HttpClient Post
onInstall:
- script: |
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
var client = new HttpClient();
var name = "some-name";
var password = "some-password";
var requestEntity = new StringRequestEntity(toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
}), "application/json", "UTF-8");
var post = new PostMethod("https://example.com/");
post.setRequestEntity(requestEntity);
var status = client.executeMethod(post);
post.releaseConnection();
if (status == HttpStatus.SC_CREATED) { // 201
return { type : "success" };
} else if (status == HttpStatus.SC_UNAUTHORIZED) { // 401
return { type: "error", message: "bad credentials" };
}
return { type: "error", message: "unknown error" };
Also, you can find many useful examples and information in the Jelastic JPS Collection repository.
Perhaps the next script will be useful for you:
https://github.com/jelastic-jps/git-push-deploy/blob/master/scripts/add-web-hook.cs
One last thing that if you don't need the exact HTTP Status, you can use an integrated "Transport" class.
import com.hivext.api.core.utils.Transport;
var name = "some-name";
var password = "some-password";
var data = toJSON({
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"domain": {
"id": "default"
},
"name": name,
"password": password
}
}
},
"scope": {
"project": {
"domain": {
"id": "default"
},
"name": "some-name"
}
}
}
});
try {
new Transport().post("https://example.com/", data, {
'Content-Type': 'application/json',
'Content-Length': data.length
});
return { type: "success" };
} catch (e) {
return {
type: "error",
message: "unknown error: " + e
};
}

YoutubeData API V3 - Error 400: required parameter - part

I'm trying to fetch data from Youtube API using jQuery and Ajax GET request with the required parameter, including "part".
The GET request is ok (code 200), however when I see the data I'm getting an error 400 "required parameter: part".
Could anyone give me some tip to overcome this issue?
This is part of my jQuery and the result of the ajax request is right below.
$(document).ready(function(){
console.log('doc ok');
$('#tag-search').submit(function(){
var search_term = {
q: "test"
};
search(search_term);
});
});
function search(search_term) {
console.log('searching ...');
console.dir(search_term);
var search_term = '';
var desireSearch = $ ('#tag').val();
var channelName = 'Iron_Maiden';
$.ajax({
method: 'GET',
url: 'https://www.googleapis.com/youtube/v3/channels?',
part : 'contentDetails',
forUsername: channelName,
key: '(My personal key)',
dataType: 'jsonp'
})
.done(function(results){
var result = results.data;
console.log(result);
});
}
And this is what I got:
jQuery1900617815546458587_1453343296717 (
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required parameter: part",
"locationType": "parameter",
"location": "part"
}
],
"code": 400,
"message": "Required parameter: part"
}
}
)
You need to use data: {} in the $.ajax request:
$.ajax({
method: 'GET',
url: 'https://www.googleapis.com/youtube/v3/channels?',
data: {
part : 'contentDetails',
forUsername: channelName,
key: '(My personal key)'
},
dataType: 'jsonp'
})
http://api.jquery.com/jquery.ajax/

EWS - A token was not recognized in the JSON content

I try to send an email via EWS using Javascript and the REST API.
The OAuth is not the problem so far.
The problem is, if I try to send the email, the Server sends this response:
"{"error":{"code":"RequestBodyRead","message":"Invalid JSON. A token was not recognized in the JSON content."}" (taken from Chrome Debug Console).
Here my Javascript, where the error occurs:
function mailIsRaus(token) {
var gottenParam = JSON.stringify(token);
var jsonObj = JSON.parse(gottenParam);
var leToken = jsonObj['access_token'];
//This is the Token from Active Directory
leToken = "Bearer " + leToken;
var Message = {
"Message": {
"Subject": "TESTING REST API EWS",
"Body": {
"ContentType": "Text",
"Content": "IT WORKED. The EWS is working my friend."
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "johndoe#something.com"
}
}
]
},
"SaveToSentItems": "true"
};
//eMailData = JSON.stringify(eMailData);
$.ajax({
type: 'POST',
beforeSend: function (request) {
request.setRequestHeader("Authorization", leToken);
request.setRequestHeader("Content-Type", "application/json");
},
data: Message,
url: 'https://outlook.office.com/api/v2.0/me/sendmail',
success: function (e) {
console.log('Email sent');
console.log(e);
},
error: function (message) {
console.log(message);
}
});
}
I strictly sticked to MSDN and now, I have no clue, why this error occurs.
If I comment out the "setRequestHeader" I get an error 401 unauthorized.
The token ist correct.
The scope is also correct.
Maybe I made an simple mistake in the "var Massage" or something...
I found the solution by myself.
I had to uncomment the following line of code to:
eMailData = JSON.stringify(eMailData);
Now it is working fine.

zombie.js xhr json always fail

I want to use zombie js to test my little node app.
I'm using the mock ressoures with zombie but when i write
body: object
in mock.the xhr always fail because of
Request Failed: parsererror, SyntaxError: Unexpected token o
when i write
body: 'json content'
xhr work well
To test this client js
var xhrGetRiver = $.getJSON("api/1/settings/rivers/fs/")
xhrGetRiver.done(function(json) {
console.log(json);
$.each(json, function(index, fsriver) {
insertFSRiver(fsriver);
});
});
xhrGetRiver.fail(function(jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
console.log("Request Failed: " + err);
});
I have write this test
var data = [];
var json = {
"id": "test",
"properties": {
"url": "/tmp",
"server": "192.168.9.2",
"port": 22,
"username": "testUser",
"password": "test",
"protocol": "ssh",
"update_rate": "15m",
"includes": "*.docx"
}
};
data.push(json);
this.browser.resources.mock('/api/1/settings/rivers/fs/', {
statusCode: 200,
headers: { 'ContentType': 'application/json' },
body: data // xhr fail
//body: '[ { "id":... ... } ]' // Work well
in app i'am using Express framework and i use res.json the array from library.
res.json seem to stringify my array

Categories

Resources