Pull Data From Other Websites With Javascript

An introduction to APIs

What's Cool About APIs?

What's Cool About APIs?

It lets us share data and create more robust websites & apps.

What is an API anyway?

  • A way to pass data
  • Ability to interface with servers of difference codebases
  • Decentralized services, degrees of separation
  • Get people interacting with you!

API: Application Programming Interface

What could I make by using an API?

Weather widget (current time, temp, conditions)

Social media tie in, eg Latest Tweets

Search box for [adoptable pets?] on your site

Send data to outside services (eg daily rainfall)

How do I find an API I can use?

  • Search for Developer Docs on your favorite services
  • Are there things you could be automating? Look for API-ready solutions
  • Carefully read terms, conditions, and limits
  • Ask companies to implement them (it never hurts)

Try here: github.com/toddmotto/public-apis

You'll get the hang of it and find that you can accomplish big things using APIs.

Like jQuery says, Write Less and Do More.

We'll create a very simple app using Javascript.

Why Javascript?

  • Any server will do (save into /var/www if you are using Apache).
  • We can keep the whole thing on one page.

Before we dive in, a little overview on GET and POST requests

GET Requests

  • Are used to load pages and sites
  • Can pass arguments through the query string only
    (ie google.com?search=cats)
  • Can be bookmarked for later

A bit like receiving a letter.

POST Requests

  • Are used to submit a form, and similar things
  • Depend on submitted data to process and display
  • Cannot be bookmarked, form must be resubmitted

A bit like sending a letter.

We'll be making a GET request today.

So let's do it

Open your text editor of choice

We'll start with a shell of a (very) basic document

Grab it at: github.com/sprise/api-demo

We'll start with a shell of a (very) basic document

We've got:

  • Head and Body tags
  • Title and utf-8 encoding metatags
  • H1 title
  • An empty div with an ID of main
  • Light styling

You can also just write this in your editor if you'd like.

Add some inline Javacript

Before the closing body tag add this:


<script type="text/javascript">

</script>

This is where our script will go.

Create a new XmlHttpRequest Object


<script type="text/javascript">

  // Create a new request object
  var xmlHttp = new XMLHttpRequest();

</script>

Set the API Url and Request Method


<script type="text/javascript">

  // Create a new request object
  var xmlHttp = new XMLHttpRequest();

  // Specify that this is a GET request and our API endpoint
  xmlHttp.open("GET", 'https://api.chucknorris.io/jokes/random'); 
		
</script>

Now, we're going to detect when the data is ready


<script type="text/javascript">

  // Create a new request object
  var xmlHttp = new XMLHttpRequest();
		
  // Every time the state changes, this will run
  xmlHttp.onreadystatechange = function() { 
			
    // Catch the data when the page has been opened
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				
				
    }
  }
		
  // Specify that this is a GET request and our API endpoint
  xmlHttp.open("GET", 'https://api.chucknorris.io/jokes/random'); 
		
</script>

Use the response JSON to populate our page


<script type="text/javascript">

  // Create a new request object
  var xmlHttp = new XMLHttpRequest();
		
  // Every time the state changes, this will run
  xmlHttp.onreadystatechange = function() { 
			
    // Catch the data when the page has been opened
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
				
      // Parse it into legit JSON
      var response = JSON.parse(xmlHttp.responseText);
				
      // Grab the wrapper element
      var main_div = document.getElementById('main');
				
      // Insert a little HTML with our new data 
      main_div.innerHTML = '<img src="'+response.icon_url+'" /> '+response.value;
    }
  }
		
  // Specify that this is a GET request and our API endpoint
  xmlHttp.open("GET", 'https://api.chucknorris.io/jokes/random'); 
		
</script>

Lastly, send the request!


		
  // Specify that this is a GET request and our API endpoint
  xmlHttp.open("GET", 'https://api.chucknorris.io/jokes/random'); 
		
  // Go!
  xmlHttp.send(null);
		
</script>

Now test in your browser.

Did you learn something new about Chuck Norris today?

What Next?

  • Learn other ways of hitting APIs (so many!)
  • Add one to a personal project and post it to the subreddit
  • Use these slides for your own presentation
  • For feedback or assistance click the link below: