github says cannot parse json while creating a repo in rest api - javascript

I'm learning REST api for github and trying to create a new repository by running a JS. Here is my function for creating a new repo: the token is generated, and all access/scopes is granted for my token.
function createNewRepo(userId, name){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": "EnableIssues",
"content-type": "application/json",
"Authorization": token,
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true,
}
};
//console.log(eval(options));
request(options, function (error, response, body)
{
var obj = JSON.parse(body);
console.log( obj );
});
}
however when running this, I find,
{ message: 'Problems parsing JSON', documentation_url: 'https://developer.github.com/v3' }
I'm not sure how exactly could the JSON be invalid.
Also, the documentation says it must include public_repo or repo which I'm also not sure how to apply here.

This for me has created the repository.
var myToken = "token INSERTHERETHETOKEN"; // <-- there must be the word token before the actual token.
var urlRoot = "https://api.github.com";
var request = require("request");
function createNewRepo(user, name, token){
var options = {
url: urlRoot + "/user/repos",
method: 'POST',
headers: {
"User-Agent": user,
// "content-type": "application/json", This is set by json:true
"Authorization": token,
"Accept": "application/vnd.github.v3+json"
},
body: {
"name": name,
"description": "This is repo creating by REST",
"homepage": "https://github.com",
"private": false,
"has_issues": true,
"has_projects": true,
"has_wiki": true
},
json: true
};
request(options, function (error, response, body) {
// Do your stuff... but notice that response
// is already a json object and you don't need to parse it.
});
}
createNewRepo("YourGithubUser", "test.repository", myToken);

Related

Get data from Google Ads API using App Script

I wanna get out campaigns reports using Google Rest API and it does'nt work in Google ads Apps script.
My code:
function main() {
const API_VERSION = "12";
const CUSTOMER_ID = "***"; //contais real custommer ID
const DEVELOPER_TOKEN = "***"; //contais real developper ID
const MANAGER_CUSTOMER_ID = "***"; //contais real manager ID
const OAUTH2_ACCESS_TOKEN = ""; //contais real ACCES TOKEN
const data = {
"pageSize": 10000,
"query": "SELECT ad_group_criterion.keyword.text, ad_group_criterion.status FROM ad_group_criterion WHERE ad_group_criterion.type = 'KEYWORD' AND ad_group_criterion.status = 'ENABLED'"
};
const url = `https://googleads.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
body: JSON.stringify(data),
"muteHttpExceptions": true
};
Logger.log(UrlFetchApp.fetch(url, options));
}
Result error:
{
"error": {
"code": 400,
"message": "Request contains an invalid argument.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.ads.googleads.v12.errors.GoogleAdsFailure",
"errors": [
{
"errorCode": {
"queryError": "UNEXPECTED_END_OF_QUERY"
},
"message": "Error in query: unexpected end of query."
}
],
"requestId": "zKBR9-dJoG9NWAx3iJea2g"
}
]
}
}
But query is valid https://developers.google.com/google-ads/api/fields/v11/query_validator
enter image description here
Could you plese help?
Thanks
I wanna get out campaigns reports using Google Rest API and it does'nt work. My code and result is above.
Based on the documentation of UrlFetchApp, 'body' is not the correct option for passing in the query. You want 'payload'.
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
"developer-token": DEVELOPER_TOKEN,
"login-customer-id": MANAGER_CUSTOMER_ID,
"Authorization": `Bearer ${OAUTH2_ACCESS_TOKEN}`
},
payload: JSON.stringify(data),
"muteHttpExceptions": true
};

NodeJS - Send JSON object parameters with node-fetch

I'm trying to create a webhook via the GitHub API. The docs say that I need to provide a config parameter, which should be an object, but I'm not sure how I can send a JSON in the URL parameters. Here's what I've tried:
fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config={"url": "https://webhooks.example.com", "content_type": "json"}`, {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
}
});
and
fetch(`https://api.github.com/repos/${repo.full_name}/hooks?config.url=https://webhooks.example.com&config.content_type=json`, {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
}
});
They both result in the following error:
{
"message": "Validation Failed",
"errors": [
{
"resource": "Hook",
"code": "custom",
"message": "Config must contain URL for webhooks"
}
],
"documentation_url": "https://developer.github.com/v3/repos/hooks/#create-a-hook"
}
How do I properly send a JSON object? I'm looking for a solution using node-fetch
When you are doing a post request, it's implied that there will be a payload and the lib you are using will be expecting a body property containing your payload.
So just add
fetch('https://api.github.com/repos/${repo.full_name}/hooks', {
method: "POST",
headers: {
Accept: "application/vnd.github.v3+json",
Authorization: `token ${account.accessToken}`
},
body:JSON.stringify(yourJSON) //here this is how you send your datas
});
And node-fetch will send your body with your request.
If you want more details on that i'll expand my answer
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods here for a quick description of different http request type (verb)

ClientId is null when calling ValidateClientAuthentication with Ajax

I have the following code that are generated by POSTMAN:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:51734/token",
"method": "POST",
"headers": {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "application/json",
"cache-control": "no-cache",
"Postman-Token": "2879f786-3b1f-42fe-8198-b2193764d165"
},
"data": {
"grant_type": "client_credentials",
"client_id": "6E1JIQDEF0M"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When you run the code above, the following code below are first executed:
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId = string.Empty;
string clientSecret = string.Empty;
ClientDTO client = null;
if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
{
context.TryGetFormCredentials(out clientId, out clientSecret);
}
if (context.ClientId == null)
{
//Remove the comments from the below line context.SetError, and invalidate context
//if you want to force sending clientId/secrects once obtain access tokens.
context.Validated();
//context.SetError("invalid_clientId", "ClientId should be sent.");
//return Task.FromResult<object>(null);
return;
}
}
The problem I have is that context.ClientId is always null, and I don't know why.
When I make the same request with C# it works:
var client = new RestClient("http://localhost:51734/token");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "db182d32-9eff-4150-815e-2fd7d10ebd58");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("undefined", "grant_type=client_credentials&client_id=6E1JIQDEF0M&undefined=", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
So why does it work with c# but not javascript? Anyone who has any idea?
Try to call like this from Javascript.
data : 'grant_type=client_credentials&client_id=6E1JIQDEF0M'

Invalid json in request body using ionic push

Couldn't find what's wrong with my req object. I got this error when trying to send push notification in the callback. Tried to link my request data using jslint.com, nothing wrong with it. Been scratching head for hours for this!
{"link": null, "message": "Invalid JSON in request body. For empty
JSON, pass '{}'.", "type": "UnprocessableEntity"}
my code as below :
var title = req.body.title,
message = req.body.message;
// Define relevant info
var ionic_api_token = 'eyJ0eXAiOTdGb-xQVQaD2sV7qTh7XNKCnwiJKV1QiLJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2MjiNC03YjE5LTQ3MzMtYjJhMy0zM2Y3MjBkYzU4MjcifQ.s3e6pCwlVUBAs8kvbO';
var device_tokens = ['d44pDarVamnNJS2cNJ2modyBxjZZxcHLlnhQN4wZkJdbgkOw96rq9EEv2WCA5MKU6do0pJoO5rsmQsBAecFt4OIFB0hhD4Dp2K-uMbjum828j-8LKtpCTtGoIDBUvYI6L'];
var ionic_security_profile = 'main';
// Build the request object
var req = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + ionic_api_token
},
data: {
"tokens": device_tokens,
"profile": ionic_security_profile,
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
},
"ios": {
"title": title,
"message": message
}
}
}
};
function callback(error, response, body) {
console.log(body)
}
request(req, callback);
});
Only thing that could cause problem are the title & message objects(probably string). Please try escaping it, like below
function escapeJson(json) {
return JSON.parse(JSON.stringify(json));
}
title = escapeJson(title);
message = escapeJson(message);
var req = {
method: 'POST',
url: 'https://api.ionic.io/push/notifications',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + ionic_api_token
},
data: {
"tokens": device_tokens,
"profile": ionic_security_profile,
"notification": {
"title": title,
"message": message,
"android": {
"title": title,
"message": message
},
"ios": {
"title": title,
"message": message
}
}
}
};

Using Facebook's Mobile Hosting API with Parse Cloud Code for App Links

I am having trouble getting App Links working with Parse.
Since my App is mobile only i wanted to use Facebook's Mobile Hosting API.
And since you need to send your Facebook App Secret with the request i wanted to do it with Parse Cloud Code.
All i coud find on the Facebook documentation was how to do it with cURL:
curl https://graph.facebook.com/app/app_link_hosts \
-F access_token="APP_ACCESS_TOKEN" \
-F name="iOS App Link Object Example" \
-F ios=' [
{
"url" : "sharesample://story/1234",
"app_store_id" : 12345,
"app_name" : "ShareSample",
}, ]' \
-F web=' {
"should_fallback" : false, }'
so this is what i came up with in cloud code
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://graph.facebook.com/app/app_link_hosts',
headers: {
'Content-Type': 'multipart/form-data'
},
body: {
access_token : "APP_ACCESS_TOKEN",
name : "iOS App Link Object Example",
ios : '[{"url" : "sharesample://story/1234","app_store_id" : 12345,"app_name" : "ShareSample",},]',
web : '{"should_fallback" : false,}'
}
the response i get is: Request failed with response code 400
now i just read that multipart/form-data is not supported withParse.Cloud.httpRequest
so is there another way to do this?
update: just found out that you can send multipart data with a Buffer,
so this is my code now
var Buffer = require('buffer').Buffer;
var access_token = new Buffer('APP_ACCESS_TOKEN','utf8');
var name = new Buffer('iOS App Link Object Example','utf8');
var ios = new Buffer('[{"url" : "sharesample://story/1234","app_store_id" : 12345,"app_name" : "ShareSample",},]','utf8');
var web = new Buffer('{"should_fallback" : false,}','utf8');
var contentBuffer = Buffer.concat([access_token, name, ios, web]);
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/app/app_link_hosts',
method: 'POST',
headers: {
'Content-Type': 'text/html; charset=utf-8'
},
body: contentBuffer
}
however i am still getting the same result :(
update2: got it working with content type application/x-www-form-urlencoded and normal body. But i think the error was somewhere in my parameters since i tested it with curl and got the same response
It took me a few hours, but I finally got it working:
// Returns the canonical url, like https://fb.me/....
Parse.Cloud.define("createAppLink", function(request, response) {
// see https://developers.facebook.com/docs/graph-api/reference/v2.5/app/app_link_hosts
var storyId = request.params.storyId + ''; // param identifying a single "post"
var appId = 'APP_ID';
var appSec = 'APP_SECRET';
var appToken = appId + '|' + appSec; // your app token
Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/app/app_link_hosts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ // you need to stringify it
access_token: appToken,
name: 'LINK TO ' + storyId, // it is needed but not public
android: [{
url: 'app://story/' + storyId, // deep link url
package: 'com.package', // your package name
app_name: 'APP' // your app name
}],
web: { should_fallback: 'false' }
})
}).then(function(httpResponse) {
// We get an id, by which we can fetch
// the canonical url with a get request
var data = JSON.parse(httpResponse.text);
var id = data.id;
return Parse.Cloud.httpRequest({
url: 'https://graph.facebook.com/' + id,
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
params: {
access_token: appToken,
fields: 'canonical_url',
pretty: 'true'
}
});
}).then(function(httpResponse) {
var data = JSON.parse(httpResponse.text);
var canonicalUrl = data.canonical_url;
response.success(canonicalUrl);
}, function(error) {
response.error(error);
})
});

Categories

Resources