Github API v3: Update file not working (404) - javascript

I'm trying to update a file using the Github v3 api. Most of the documentation I could find was based on the older API. I want to utilize: https://developer.github.com/v3/repos/contents/#update-a-file
I first grab the file using:
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function (data) {
var jsonFile = data.content;
sha = data.sha;
var decodedJson = atob(jsonFile);
var parsedDecodedJson = JSON.parse(decodedJson);
parseData(parsedDecodedJson);
},
error: function(error){
alert.addClass('alert-danger').removeClass('hidden').html('Something went wrong:'+error.responseText);
}
});
Which works perfectly.
After editing the file, I try to update the file.
On my submit I post the following using jQuery:
var postData = {
"message": "Update",
"content": btoa(obj),
"sha": sha,
"branch":"gh-pages"
};
$.ajax({
url: "https://api.github.com/repos/"+owner+"/"+repo+"/contents/"+path,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "user" + btoa(owner+":"+passwrd));
},
type: 'PUT',
data: postData,
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log("Success!!!", data);
},
error: function(error){
console.log("Cannot get data", error);
}
});
All the variables contain the expected values. Regardless, I keep getting a 404.
I know the API more often than not returns a 404 instead of something like a 403 as stated here: https://developer.github.com/v3/#authentication But it makes debuggin nearly impossible in my opinion. I have no clue what I'm doing wrong here. Thanks!

The only way I was able to do it is to make the entire round trip.
I used a javascript Github API wrapper
Luckily I found this article in which the bulk of the work was already been done. Props to Illia Kolodiazhnyi.
In the end. I ended up with this:
Handler on top of github api plugin
Usage:
var api = new GithubAPI({ token: token});
api.setRepo(owner, repo);
api.setBranch(branch).then(function () {
return api.pushFiles(
'CMS Update',
[
{
content: JsonData,
path: path
}
]
);
}).then(function () {
console.log('Files committed!');
});

Related

Firebase Creating Dynamic Links with the REST API call using Javascript giving 400

I am trying to create Firebase Dynamic Links with REST API using simple Javascript ajax code, but every time I am getting 400 bad request, though I have tried and implemented the documentation described at https://firebase.google.com/docs/dynamic-links/create-links. I couldn't find any solution for this.
Whats wrong I am doing here please help.
Here is my code
<!DOCTYPE html>
Change Content
<script>
function loadDoc() {
var params = {
longDynamicLink:
"https://thepary.page.link/?link=http://www.example.com/&apn=com.example.android&ibi=com.example.ios",
dynamicLinkInfo: {
domainUriPrefix: "https://thepary.page.link",
link: `https://threads-1511.web.app/threads/`,
iosInfo: {
iosBundleId: "com.bundleId",
iosAppStoreId: "1512677811",
iosIpadBundleId: "com.bundleId",
},
androidInfo: {
androidPackageName: "com.bundleId",
},
socialMetaTagInfo: {
socialTitle: `A thread by s`,
socialDescription: `s`,
socialImageLink:
"https://firebasestorage.googleapis.com/v0/b/threads-1511.appspot.com/o/playstore.png?alt=media&token=896f4fe6-2882-442e-b15c-3767d61b8a70",
},
},
suffix: {
option: "SHORT",
},
};
$.ajax({
url:
"https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=[APIKEY]",
type: "POST",
data: params,
dataType: "json",
contentType: "application/json",
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
},
});
}
</script>
Since API expects contentType: "application/json",
You need to data: JSON.stringify(params)

How to make a REST API Request with Ajax and session token?

I'm having trouble following an API Guide using AJAX. I have successfully got the session token from the login api as the session token is needed to make requests to GET/POST data.
Code to get the session token:
var sessionToken = null;
$.ajax({
url: '<API-URL>/1/json/user_login/',
data: {
'login_name' : 'USERNAME',
'password' : 'PASSWORD'
},
type: 'GET',
dataType: 'json',
success: function(data) {
sessionToken = data.response.properties.session_token;
$("#result").text("Got the token: " + sessionToken);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
On successful, we get the session token: D67ABD0454EB49508EAB343EE11191CB4389255465
{response: {…}}
response:
properties:
action_name: "user_login"
data: [{…}]
action_value: "0"
description: ""
session_token: "D67ABD0454EB49508EAB343EE11191CB4389255465"
__proto__: Object
__proto__: Object
__proto__: Object
Now that I have a valid session token, I can now make requests to get data. I'm trying to get driver data using the following code:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
According to the documentation, I need to use POST instead of GET in order to get vehicle details in the response and pass the session token as a parameter:
Unfortunately it seems to return blank data when using GET and Permission denied when using POST. I've tried sending the parameters as an array like the documentation but that fails also. I've tried passing the session token as Authorisation but still get no response.
The only help I got from the API support team was: "POST can’t be with parameter query on the end point."
What am I doing wrong?
Any help is appreciated. Thanks!
I don't know what service/api you're trying to call, but from the error message you've posted and the brief documentation it looks like you're structuring your url wrong:
$.ajax({
url: '<API-URL>/1/json/api_get_data/',
data: {
'license_nmbr' : vrn,
'session_token' : sessionToken
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});
You're including the action parameter as part of the url by the looks of things when the doc you posted implies it should be part of the data (and the error they sent you of "POST can’t be with parameter query on the end point." also supports this). So try the following: (of course without seeing more of the docs it's difficult to know if your actual base url is correct)
$.ajax({
url: '<API-URL>/1/json/',
data: {
'action': {'name':'api_get_data',
'parameters': [ {'license_nmbr' : vrn }],
'session_token' : sessionToken
}
},
type: 'POST',
//dataType: 'json',
success: function(data) {
//var obj = JSON.parse(data);
console.log(data);
},
error: function(err) { console.log(err); },
beforeSend: setHeader
});

building wikipedia viewer with their API, always get error

I can't seem to get it working, I followed other code, and it didn't seem to get success, I then written it letter to letter, stil can't get success.
The url works great, I can put it in browser and it will show me the array which I need.
$(document).ready(function(){
$("#submitSearch").on("click", function() {
var searchInput = $("#txtName").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + searchInput;
var wikiItemArray = [];
$.ajax({
url: url,
type: "GET",
async: false,
dataType: "json",
success: function (data) {
console.log(data);
},
error: function(error){
console.log("There was an error somewhere in &.ajax: " + url);
}
});
});
});
Change the dataType from "json" to "jsonp".
That api is not CORS enabled but does serve jsonp

How to use an API Key for an Ajax call?

I am trying to include an API key for the first time from New York Times API ( http://developer.nytimes.com/) and use ajax to fetch news from it to populate a local website but I'm not seeing any results. I was told to Make sure your API key is set in the URL's query parameters but I'm not sure how to do it.
?api-key=your-key
Here is what I have done:
// Built by LucyBot. www.lucybot.com
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "111111111111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
I need to see the url in json format for various stories such as business, technology, etc and use them for an ajax call.
Try this I am getting data from this
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "11111111111111111111111"
});
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can also try like as follows
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
$.ajax({
url: url,
method: 'GET',
dataType: 'JSON',
data: {
'api-key': '11111111111111111'
},
success: function(data) {
console.log(data)
},
error: function(err) {
console.log('error:' + err)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Its not a good practice expose API Key directly in client-side context.
I strongly recommend to create an abstraction layer between the browser and the API.
The idea is target the AJAX request to one own backend action, like:
var url = "www.mydomain.com/api/articlesearch";
$.ajax({
url: url,
method: 'GET',
}).done(function(result) {
console.log(result);
}).fail(function(err) {
throw err;
});
And inside the backend (/api/articlesearch) we place the request that target to NY Times, using the API Key
This way you get a more suitable code for javascript, keeping the responsibilities correctly distributed.
PS: If you want it even more safe, you can define the API Key using env variables. Here is an example made in Ruby (just for figure it):
# Inside ApisController
def articlesearch
response = RestClient::Request.execute(
method: :get,
url: 'https://api.nytimes.com/svc/search/v2/articlesearch.json',
headers: {api_key: ENV['API_KEY']})
render json: response
end
Using this approach the API Key will also not be present in GIT repository :)
Well, you should try it this way. It should give you a result without cross-origin errors:
$.ajax({
type: 'GET',
url: 'http://api.nytimes.com/svc/search/v2/articlesearch.json',
data: {
'q': queryString,
'response-format': "jsonp",
'api-key': nytApiKey,
},
success: function(data) {
// passed function object for data processing
console.log(data);
},
error: function(err) {
console.log('error:' + err)
}
});

Javascript with SharePoint 2013 REST Endpoint "INSERT" into List?

Here are what i'm going to use:
SharePoint 2013
Javascript
REST Endpoint
SharePoint List (called: "Announcements")
WebSite (called: "example.com")
Refs:
http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/
https://msdn.microsoft.com/EN-US/library/dn292552.aspx
Very simply:
How do i INSERT a new item (row) inside the List please?
I tried:
$.ajax({
url: "https://example.com/_api/web/lists/getbytitle('Announcements')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify( { '__metadata': { 'type': 'SP.Data.AnnouncementListItem' }, "Title": "New Announcement!" } ),
headers: {
"Accept": "application/json;odata=verbose",
"Authorization": "Bearer " + accessToken
"X-RequestDigest": form digest value,
"IF-MATCH": etag,
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
Then i know a lot of things go wrong especially in headers section. But what does it mean by:
Authorization
accessToken
X-RequestDigest
IF-MATCH
.. and then HOW TO get these values (with JavaScript)? So that:
What are always the exact required fields there?
And how/where to get these values from?
I still can not find a simple and complete example about doing this Update / Insert properly.
So there are two ways that I have used to submit an item to a list, the jQuery library SPServices and REST API's. SPServices is really well documented here. Using REST API's is much faster and pretty easy too!
function createListItem(itemProperties, success, failure) {
$.ajax({
url: "https://example.com/_vti_bin/listdata.svc/Announcements",
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
data: JSON.stringify(itemProperties),
headers: {
"Accept": "application/json;odata=verbose"
},
success: function(data) {
success(data.d);
},
error: function(data) {
// failure(data.responseJSON.error);
alert("error");
}
});
}
First thing I am doing above is creating a function that you can call whenever you want to create a new list item. The parameter itemProperties can be populated with the fields which you need, see below.
var Title = "Title";
var Answer = "Answer";
var userid = _spPageContextInfo.userId;
var taskProperties = {
'Title': Title,
'Answer': Answer,
'UserId': userid
};
Then all we have to do is call this function with the new variable we just declared.
createListItem(taskProperties, function(task) {
alert("Thank you for your input!");
},
function(error) {
console.log(JSON.stringify(error));
}
);
Actually jsfiddle which you have posted in the previous commend is not the REST . you just use the SharePoint client object model. find below the REST API model I hope it will work
var cat = {
"__metadata": { "type": ItemType },
"Title": "GenIT-Issue",
}
$.ajax({
url: _spPageContextInfo.siteAbsoluteUrl + "/_api/web/lists/getbytitle('Tickets')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(cat),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
},
error: function (data) {
}
});
I run this code inside my SharePoint page so there is no authentication required. it will run on current user privilege

Categories