Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of using github API from javascript

I've been searching on the web for some time and couldn't find an example of how to use the GitHub API from plain client-side javascript (no node-js, jquery etc). I wanted something like authenticate then push a blob, put as simply as possible so I can understand it. Shouldn't be too complicated, I bet you can do that in a dozen lines of code but I don't know a lot about ajax, json and jsonp.

Can you provide an example to get me started?

Thanks!

edit: found this: http://blog.vjeux.com/category/javascript, but I'm still confused as to what are exactly the steps of the process.

like image 351
Giovanni Funchal Avatar asked Apr 26 '12 20:04

Giovanni Funchal


People also ask

Can we use API in JavaScript?

An API is simply a medium to fetch or send data between interfaces. Let's say you want to make an application that provides the user with some real-time data fetched from the server or maybe even allows you to modify or add data to some other endpoint.

How do I get my GitHub API URL?

Method: select GET. URL: enter as https://api.github.com/user/repos as URL. Request Name: give a user-friendly name to this request in Paw, like "GitHub User Repositories"


1 Answers

If you're looking to use with vanilla JavaScript (i.e. no framework), you need to play around with the XMLHttpRequest object. The XMLHttpRequest provides the core for AJAX implementations.

Despite the XMLHttp prefix, you're not limited to XML or HTTP. You can retrieve any data type (such as JSON) and use other protocols such as FTP.

Say we'd like to GET your user information from GitHub. From a browser, we can easily make the request by visiting https://api.github.com/users/funchal. Sending an HTTP request in JavaScript is just as simple with XMLHttpRequest:

// Create a new request object var request = new XMLHttpRequest();  // Initialize a request request.open('get', 'https://api.github.com/users/funchal') // Send it request.send() 

If you give this a go from a JavaScript console, you might feel a bit disappointed: nothing will happen immediately. You'll have to wait for the server to respond to your request. From the time you create the instantiate the request object till when the server responds, the object will undergo a series of state changes denoted by the value of the readyState property:

  • 0 UNSENT: open() uncalled
  • 1 OPENED: send() uncalled
  • 2 HEADERS_RECIEVED: headers and status are available after a send()
  • 3 LOADING: the responseText is still downloading
  • 4 DONE: Wahoo!

Once all is finished, you can check the response attribute for the data:

request.readyState // => 4 (We've waited enough) request.response // => "{whatever}" 

When using XMLHttpRequest#open(), you have a few options to consider. Here's the method signature:

void open(    DOMString method,    DOMString url,    optional boolean async,    optional DOMString user,    optional DOMString password ); 

The third parameter, which defaults to true, dictates whether the response should be made asynchronously. If you set this to false, you'll have to wait until the response is complete for #send() to return, and you'll pay the price of blocking your whole program. As such, we code in an asynchronous fashion so that our program remains responsive even while we wait. This asynchronicity is achieved by using and event listeners (a.k.a. event handlers) and callback functions.

Say we want to simply dump the response to the console once it arrives. We first need to create a callback function that we'd like to execute onload:

function dumpResponse() {   // `this` will refer to the `XMLHTTPRequest` object that executes this function   console.log(this.responseText); } 

Then we set this callback as the listener/handler for the onload event defined by the XMLHttpRequest interface:

var request = new XMLHttpRequest(); // Set the event handler request.onload = dumpResponse; // Initialize the request request.open('get', 'https://api.github.com/users/funchal', true) // Fire away! request.send() 

Now since you'll be receiving the data as a string, you'll need to parse the string with JSON.parse() to do anything meaningful. Say I want to debug the number of public repositories you have along with your name. I can use this function to parse the string into JSON, and then I can pull the attributes I want:

function printRepoCount() {   var responseObj = JSON.parse(this.responseText);   console.log(responseObj.name + " has " + responseObj.public_repos + " public repositories!"); } var request = new XMLHttpRequest(); request.onload = printRepoCount; request.open('get', 'https://api.github.com/users/funchal', true) request.send() // => Giovanni Funchal has 8 public repositories! 

See the W3C spec and the Mozilla Developer Network for more info on XMLHttpRequest.

like image 130
fny Avatar answered Sep 23 '22 22:09

fny