APIs allow you to interact with some big data platforms like twitter and pull their data to your application, then display it.
To pull data from a website, they first have to offer a web API. APIs are just a URL that you can make a request to that will respond with a .JSON response. .JSON format is "JavaScript Object Notation". This .JSON format is almost identical to the local storage project we used in this tutorial. In that project, we updated the local storage from our array and also updated the site from the local storage using stringify
to store & parse
to pull it out - in this case we will do it almost the same way treating local storage as if it were an API.
You may hear what we are doing here called ajax
which stands for "asynchronous, javascript, and xml" - where xml is a formatting type but typically, for most use cases, you will do that using json.
Note: that some APIs require authentication, we aren't going to get into that in this article. This is intended to be a brief overview of APIs - you will likely not be an API guru by the end of this article but, you will have an introductory understanding.
Using The GitHub API
Head over to https://api.github.com/users and take a peek. The formatting you will see is called JSON and it should strike you as familiar - almost as if it were structured just like Javascript objects as mentioned before. For the best human reading experience, head over to the chrome extension store and download JSON Viewer which will format the JSON file in a format you can easily read. You can add your username at the end of the URL path ( ie /yourusername
) and see your own github json.
You can learn a bunch more about the Github API in their documentation if you'd like to implement any of this project into your own portfolio. Some cool things you could do is show off your star ratings, a link to your repo, or show off your commit map.
Let's create a basic HTML file inside a new project folder and do all this within a <script>
tag.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>AJAX</title> </head> <body> <p class="user">Loading...</p> <img class="image"> <script> // SCRIPT GOES HERE! </script> </body> </html>
// SCRIPT GOES HERE
Inside that script tag we want to establish a variable that calls the endpoint. An endpoint is the URL you are pulling the API from.
const endpoint = 'https://api.github.com/users/drewlearns';
You can use back-ticks, single quotes, or double quotes for this, doesn't matter.
We want to use a built in library to every browser called fetch();
and you pass it the endpoint which will give you a promise.
const drewPromise = fetch(endpoint); console.log('drewPromise');
If you haven't already, install live server extension for visual studio code like this and open up that HTML file we created.
Let's open that up in the browser's console log. You can see the "/users" request on the network tab. If you click on it, you will see headers which should show a "200" code meaning it processed the server request without an error. On it's preview tab, you can see all of the .json file's content.
We want to use a .then
statement to wait for the .fetch
promised command. That will load the endpoint and then we need to provide it a .catch
for error handling incase it doesn't load.
const drewPromise = fetch(endpoint); drewPromise.then(response => { //response return response.json(); // converts response to object }).then(data => { console.log(data, data.blog, data.name, data.location); }).catch(handleError);
Let's display some information. Add a <p>
on the html document.
const drewPromise = fetch(endpoint); const userElement = document.querySelector('.user');const imgSrc = document.querySelector('.image');
drewPromise.then(response => { //response return response.json(); // converts response to object }).then(data => { console.log(data, data.blog, data.name, data.location); userElement.textContent = `${data.name} - ${data.blog}`;imgSrc.src = `${data.avatar_url}`;
}).catch(handleError);
Bonus: We can refactor using async & await and add some error handling like this:
const baseEndpoint = 'https://api.github.com'; const usersEndpoint = `${baseEndpoint}/users`; const userElement = document.querySelector('.user'); const imgSrc = document.querySelector('.image'); async function displayUser(username) { userElement.textContent = "Loading..." const response = await fetch(`${usersEndpoint}/${username}`); const data = await response.json(); userElement.textContent = `${data.name} - ${data.blog}`; imgSrc.src = `${data.avatar_url}`; }; function handleError(err) { console.log('ERROR!!!'); console.log(err); userElement = "Error - Something Went Wrong!" }; displayUser('drewlearns').catch(handleError);
Final Thoughts
If you have been following along with my articles, then you will have learned so much Javascript already. We started with basic function creation and advanced along into Scope, Hoisting, and Closures, Dom Manipulation, event listeners, new, this, callbacks, promises, and now we are able to use data from other people's work and pull it into our very own projects using APIs. You are well on your way to becoming a front end Javascript developer with the tools we have demonstrated so far. In the next article we are going to work with CORS and Recipes.
If you found this article helpful, share/retweet it and follow me on twitter @codingwithdrewk! There is so much more in Wes' courses I think you will find valuable as I have. I'm learning so much and really enjoying the course, Wes has an amazingly simple way to explain the difficult bits of Javascript that other courses I've taken could only wish. You can view the course over at WesBos.com. (I am in no way getting any referrals or kickbacks for recommending this)
Drew is a seasoned DevOps Engineer with a rich background that spans multiple industries and technologies. With foundational training as a Nuclear Engineer in the US Navy, Drew brings a meticulous approach to operational efficiency and reliability. His expertise lies in cloud migration strategies, CI/CD automation, and Kubernetes orchestration. Known for a keen focus on facts and correctness, Drew is proficient in a range of programming languages including Bash and JavaScript. His diverse experiences, from serving in the military to working in the corporate world, have equipped him with a comprehensive worldview and a knack for creative problem-solving. Drew advocates for streamlined, fact-based approaches in both code and business, making him a reliable authority in the tech industry.