What's Cool About APIs?
API: Application Programming Interface
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)
Try here: github.com/toddmotto/public-apis
Like jQuery says, Write Less and Do More.
A bit like receiving a letter.
A bit like sending a letter.
Grab it at: github.com/sprise/api-demo
We'll start with a shell of a (very) basic document
You can also just write this in your editor if you'd like.
Before the closing body tag add this:
<script type="text/javascript">
</script>
This is where our script will go.
<script type="text/javascript">
// Create a new request object
var xmlHttp = new XMLHttpRequest();
</script>
<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>
// 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>
Did you learn something new about Chuck Norris today?