Yesterday we built apps that consumed 3rd party APIs (Unsplash, Open Weather, Quotes). Your mini-project prompt is an open-ended one: work together as a group, make something cool using a 3rd party API of your choosing! You should each make individual apps, but work together as a group.
Basically, an API is a service that provides raw data for public use.
API stands for "Application Program Interface" and technically applies to all of software design. The DOM and jQuery are actually examples of APIs! Since the explosion of information technology, however, the term now commonly refers to web URLs that can be accessed for raw data.
APIs publish data for public use. As third-party software developers, we can access an organization's API and use their data within our own applications.
Q: Why do we care?
Why recreate data when we don't have to? Think about past projects or ideas that would be easier if you could pull in data already gathered elsewhere.
APIs can provide us with data that would we would otherwise not be able to create ourselves.
As we move into building single page applications, now is the perfect time to start understanding how to obtain data on the client side and then render it on the browser.
Sometimes that's all we need. All this information, from all these browsers and all these servers, has to travel through the network. That's almost certainly the slowest part of the request cycle. We want to minimize the bits. There are times when we just need the data. For those times, we want a concise format.
JSON stands for "JavaScript Object Notation" and has become a universal standard for serializing native data structures for transmission. It is light-weight, easy to read and quick to parse.
{
"users": [
{"name": "Bob", "id": 23},
{"name": "Tim", "id": 72}
]
}
Remember, JSON is a serialized format. While it may look like an object, it needs to be parsed so we can interact with it as a true Javascript object.
APIs are published everywhere. Chances are good that most major content sources you follow online publish their data in some type of serialized format. Heck, even Marvel publishes an API. Look around for a "Developers" section on major websites.
That sounds hard. Can't you just give me a freebie?
Try the Programmable Web API Directory or the Public APIs Directory.
While the majority of APIs are free to use, many of them require an API "key" that identifies the developer requesting data access. This is done to regulate usage and prevent abuse. Some APIs also rate-limit developers, meaning they have caps on the free data allowed during a given time period.
Try hitting the Giphy API...
It is very important that you not push your API keys to a public Github repo.
This is especially true when working with Amazon Web Services (AWS). Here's an example of a stolen key horror story.
Axios is a Promise based HTTP client for the browser and node.js. We use Axios to request data from 3rd party APIs (or our own seperate API server). To use, include the library in your index.html
ABOVE your custom script file!
<body>
...
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="<YOUR-SCRIPT-FILE.js>"></script>
</body>
axios({
method: 'GET',
url: 'https://randoom_dev.api.com/random_api_endpoint_url'
})
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
Now we need to tell our AJAX method what to do next. We can do this by doing something with the return value, which comes in the form of a promise.
You can think of them as an IOU the the asynchronous nature of Javascript. It's like when you order a pizza. You place your order and are given receipt as an IOU until they prepare your order. In the meantime, you can check your phone, grab a drink, go wash your hands, etc. When your food is ready and delivered, the promise is fulfilled.
What other types of async operations can you think of in real life?
We can use promise methods to tell the axios()
request what to do if the request is successful or not. In this case, we are going to add two...
A promise method for when the Axios call is successful...
.then(response => {
console.log("Axios request success!");
console.log(response);
});
Q: What are we passing into the `.then` promise method? Does this remind you of anything we've done previously in class?
.then
requires a callback that determines what we do after a successful AJAX call.
A promise method for when the Axios call fails...
.catch((error) => {
console.log("Axios request fails!");
console.log(error)
});
.catch
requires a callback that determines what we do after an unsuccessful AJAX call.
-
You may need to add this chrome extension to bypass CORS errors. Be sure to turn it off once you are done working on the lab.
-
Append
https://cors-anywhere.herokuapp.com/
to the front of your api endpoint. For example:https://cors-anywhere.herokuapp.com/https://dog.ceo.api.com/random/images
Postman allows us to test out API endpoints before we start bulding the front-end of our application in React.
We can only use the browser for GET
requests. If we want to test out any other type of HTTP request like POST
, PUT/PATCH
, or DELETE
then we must use a tool like Postman.
It is much easier to test out and confirm these HTTP requests with Postman first instead of building an entire front-end with views, forms, buttons, links, etc. Way too many points of failure!
Take 25 minutes to explore the documentation for an API. In particular, think about what you see in the URL and the API response itself.
There's an API for pretty much everything. You can search for more at Mashape or check out these public APIs
If you find yourself spending more than 25 minutes just getting the API to talk back to you, you're spending too much time.
- Locally,
mkdir
andtouch
html, js, and css files. - Set up your HTML and CSS. Figure out what you want your app to look like. Be sure to include Axios and link up your files.
- Create your Axios call. Just make sure it's working -- don't worry about handling the response yet.
- Extract information from your response. How do you go about accessing it?
- Handle API Response. What are you going to do with the API response? How will you render it in your HTML/CSS?
- Axios error handling. What will your program do when your API call doesn't work?
Your app must have at minimum:
- A form to accept user input for whatever API you choose
- Incorporate at least 2 endpoints from your API
In the Dog API App, we could click a button to get a random dog image OR we could type in a specific breed in an input box and make a request for a specific random dog pic. This required the use of two endpoints.
Going above and beyond the basic implementation is desirable, should you have the time. Feel free to enhance your project with any of the following features:
- Add buttons that a user can click to get the specific information he/she wants (e.g. - 5 day, today's weather, a map, etc)
- Add a "loading" animation while the data is gathered from the API
- Implement some of the jQuery methods you've learned (
fadeIn()
,fadeOut()
, etc.) - Host your application on githubpages
- Implement Google Maps
- Implement Bootstrap
-
Wireframe Make a drawing of what your app will look like.
-
Break the project down into different components (data, presentation, views, style, DOM manipulation) and brainstorm each component individually.
-
Use your Development Tools (console.log, inspector, alert statements, etc) to debug and solve problems
-
Commit early, commit often. Don’t be afraid to break something because you can always go back in time to a previous version.
-
Consult documentation resources (MDN, jQuery, etc.) at home to better understand what you’ll be getting into.
-
Don’t be afraid to write code that you know you will have to remove later. Create temporary elements (buttons, links, etc) that trigger events if real data is not available. For example, if you’re trying to figure out how to change some text when the game is over but you haven’t solved the win/lose game logic, you can create a button to simulate that until then.