# APIWebApp **Repository Path**: mirrors_HubSpot/APIWebApp ## Basic Information - **Project Name**: APIWebApp - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2020-09-24 - **Last Updated**: 2026-01-24 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # APIWebApp Check it out at: https://enigmatic-falls-78431.herokuapp.com/ _Note: Unlike with the Base Web App, you shouldn't fork and clone the code in this repo onto your machine. Instead, try to follow the instructions below, using the code in this repo as a reference._ ## All about APIs First of all — what is an API? The actual definition of an API is pretty broad — APIs are a set of operations—with specific inputs and outputs—used for interacting with something, like a database, web service, or hardware. For example, let's say you wanted to display Beyonce's Twitter feed on your website. You could use the Twitter API to grab the tweet history of a specific user (in this case, Beyonce). Most large software companies like Google, Twitter, Facebook, and even HubSpot have APIs that let you use their services and data in your own applications. Many different kinds of data can be accessed via an API — weather, movie information and reviews, sports stats, restaurants, maps, Beyonce's tweets, and so on. If you're wondering if an API exists for some form of data you’d like to incorporate into your app, give it a search. Chances are there's an API for it. ### How APIs work Much like using HTTP, or Hyper Text Transfer Protocol, to request a website, the data from most web APIs can be accessed by sending an HTTP request to a URL. There are a few types of HTTP methods. Some popular ones are `GET`, `POST`, `DELETE`, and `PUT`. `GET` is the most commonly used type — it's for retrieving data from a service, like reading a specific item from a database. `POST` is for sending data to a service, usually to create something new in a database. This means that `POST` methods also contain a payload with the information you want to send. We won’t go through what all the other methods do right now, but check out the Resources section below for an in-depth explanation of each method type. ### Making the request Let’s explore using a `GET` request to grab the weather data for a given city. This means that your request will be read-only — it won’t actually change any of OpenWeatherMap's data. While most APIs use HTTP requests, APIs all have different specifications for how developers can interact with them. Each API has its own URL structure and rules for what kinds of requests it will accept. For example, to get the weather for Boston, you send a `GET` request to this URL. ``` https://api.openweathermap.org/data/2.5/weather?q=Boston&units=imperial ``` This URL is a typical example of what a request to a web service usually looks like. First, you start off with the protocol: HTTP or HTTPS. Then you have some base URL — in this case, `api.openweathermap.org/`. Then you add more specific paths to tell the API exactly what information you want. In this case, adding `data/2.5/weather` to the URL means you want the current weather for a location. Then, you have the query parameters, like `?q=Boston&units=imperial`. They come after a question mark, are formed by key/value pairs, and are separated by ampersands. These query parameters are a useful way of specifying the information you want to the server so that it sends back the correct data. The data that the API returns will also be totally different depending on the API. Most web APIs return data in the JSON format, which is a very simple object format that uses key-value pairs. OpenWeatherMap returns a large JSON object, which looks like this. By understanding the structure of a JSON object, you can easily take that object and pull out the information you want. ``` { "coord":{"lon":-71.06,"lat":42.36}, "weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}], "base":"cmc stations", "main":{"temp":37.42,"pressure":1029,"humidity":57,"temp_min":33.8,"temp_max":50}, "wind":{"speed":8.05,"deg":60}, "rain":{"1h":0.3}, "clouds":{"all":1}, "dt":1459956213, "sys":{"type":1,"id":1801,"message":0.0063,"country":"US","sunrise":1459937777,"sunset":1459984620}, "id":4930956, "name":"Boston", "cod":200 } ``` A different weather API would probably return similar data, like the temperature, wind speed, chance of rain, and so on — but it would likely return a JSON object in a completely different format. ### Documentation The best way to learn how to use a certain API is to go to its website and read the documentation. Most APIs will provide instructions for the different kinds of requests you can send, and what information will be sent back. OpenWeatherMap has extensive docs detailing how to structure a request and what kinds of weather data it’s capable of returning. ### Authorization Most APIs require some form of authorization. By letting only authorized users make requests, it better protects the API from abuse. Usually, you can get authorization by making an account with the service and getting an API key, which is sometimes also called an access token. This is a string you send along with the request — usually as a query parameter like `apiKey=your api key` — that lets the API know you're an authorized user. APIs all have their own way of doing this and have instructions on how to get started in their documentation. API keys are sensitive information, since they dictate how you can access different services. There are bots that continuously scrape GitHub looking for API keys to abuse. This means you should get in the practice of NOT exposing them in your code on GitHub. You can hide your API key by setting it as an environment variable on Heroku. This means Heroku will store the contents of that variable securely and will replace the variable with the real value when running your app. Finally, to access an API and use its data in your app, you’ll need a way to actually send a request to it and handle the data it returns. You’ll use AJAX to send the request to OpenWeatherMap. AJAX is a technique for sending and receiving data from a server. One useful feature of AJAX is its success and error handlers. These are functions that get called based on the result of your API request. The success handler function will get called when the request goes smoothly and comes back with the desired data. In your case, the function will take the weather data, pull out the information you want, and display it on your page using jQuery. The error handler function is called when something goes wrong. This is extremely important when using APIs, as requests can sometimes run into an error. In most cases, they’ll return some form of error message that you can display to your user. With this information, you now have enough baseline knowledge on APIs to start using them. ## Part 1: Adding the OpenWeatherMap API With a working knowledge of APIs, let’s dive into reading API documentation, setting up your environment variables, and making API calls to retrieve data and display it in your web app. Today we’ll be using the OpenWeatherMap API as an example. We chose this service because it’s simple and free to use. If you want to use another API, the steps you’ll take today should apply to most APIs. If you're not familiar with APIs, we’d recommend staying away from more complicated ones like Google and Facebook. Instead, stick with something a bit simpler for now to practice. #### 1. Create an account Go to “openweathermap.org” and click “Sign Up.” Enter your information to create your account. #### 2. Find your API Key Next, you need your API key. Your API key is like a passcode that gets you access to an API. On the OpenWeatherMap website, you can find it by clicking on “API Keys.” Your default API key lives here — it’ll look like a bunch of jumbled numbers and letters. #### 3. Hide your API Key Next, for security reasons, let’s make sure that Heroku knows your API key without listing it anywhere in your code. Copy that API key, then head to your terminal. Type, the following, then hit enter. ``` heroku config:set API_KEY=WhateverYourAPIKeyIs ``` _Remember that you must stop your server in order to do this. If your server is still running from before, you can press control + c to halt it._ Next, save that API key variable locally in a file named `.env`. This file will never be pushed to Github or Heroku; the web app will read from this file locally, and will pull it from Heroku's own configuration system once deployed. This way, you can use `API_KEY` in your local environment and on Heroku without actually having it in your code. To do that, run: ``` heroku config:get API_KEY -s >> .env ``` Next, because you’ll need to use the API key inside of your app when setting up your API request, let’s set it as a variable. Go to your `head.ejs` file, and put it before the reference to your `main.js` file. This way, you make sure the code you write later on in your `main.js` file can use the variable. Inside a `