Get the inside scoop on the 5 most common APIs you use daily (with a Python Build Example!)
Tags: beginners, api, python, productivity
Published: 2023-02-22 04:52:27

Yes! Of course, every person has got to have some API love in their lives. Without it, what is life?

Let's give a cheesy joke a go. Ready? 

Why did the chef start using **APIs**?

They realized that APIs could help them streamline their food delivery process and get delicious meals to their customers faster!

<img width="100%" style="width:100%" src="https://media.giphy.com/media/k4E9H7oRa6vde/giphy.gif">

Haha, what? Come on! Did you at least crack a smile? Since I can't see you, I'll assume you were rolling on the floor laughing. 

Let's get into some APIs we use and some examples of their usage:

**Google Maps API**: 
Have you ever used Google Maps to find directions to a location? Google Maps API allows other apps to use Google Maps to help you find your way around. In other words, apps like Uber, Lyft, or food delivery services can use Google Maps to help you get to your destination quickly and easily.

**Facebook API**: 
The Facebook API allows other apps to access Facebook data, like your profile or pictures. In other words, you can use apps like Instagram or Spotify to share your favorite music or photos with your friends on Facebook without ever leaving the app.

**Twitter API**: 
The Twitter API allows other apps to interact with Twitter, like scheduling tweets or tracking your followers. In other words, you can use other apps to manage your Twitter account and keep track of all your social media in one place.

**OpenWeatherMap API**: 
The OpenWeatherMap API provides weather data to many apps, including weather apps or travel apps, to help you plan your day or vacation. In other words, you can smoothly check the weather before leaving your house or planning a trip to another city.

<u>**My Personal Favorite**</u>
**Yelps Fusion API**: 
The Yelp APIs gives information about businesses and locations in your desired area. In other words, when you navigate to Yelp's website or mobile app, you can search for business reviews, photos, ratings, and any business details that are important to you. 

APIs are necessary because they allow all your favorite apps and services to communicate with each other, which makes it possible for different companies to provide an encompassing experience for users. 

If APIs didn't exist, it would be difficult for apps and services to communicate with each other leading to having a mundane experience across different apps and services. Plus, it would mean that apps would have to build their APIs from the ground up, which would be expensive, most importantly, time-consuming. 

For those curious about building APIs, there are web frameworks you can read up on like:
- Flask, Django, FastAPI for Python, 
- Express.js for Node.js, 
- Ruby on Rails for Ruby, 
- ASP.NET for .Net 

There are several others, but these are a few options. Everyone has their creative way of building APIs, but I figured it would be good to share a quick example of what this would look like in Python using Flask.

If you aren't familiar with Flask, here's a short and simplified bulleted list:

- It's a tool used for creating websites and web app with Python
- Makes it easier to create different parts of a website
- Helps organize the different parts of a website
- Allows adding extra features to a website, like a login system or database.
- Makes it easier to get information from people who visit a website, like a search term or form submission

**Now for the good stuff**

Assuming your terminal path points to the working project folder

1. Do a ``pip install Flask``
2. Create a new file within that directory folder. 
3. Add ``from Flask import Flask`` to import the Flask class at the top of the file.
4. Create an instance of the Flask class inside of your file and then give your API a name like so ``app = Flask(__name__)`` 

If you are like me, there may have been some internal self-talk like, "create an instance of the flask class, but why?" Through my research, I found that the ``Flask`` class represents your app, and by creating the Flask class instance, you can define your routing and other functionalities. If you do not, well, your app will not work.

After that I was like:
<img width="100%" style="width:100%" src="https://media.giphy.com/media/clspXK4twFiGjTwxOZ/giphy.gif">

5. Next, make sure to define your API endpoint by defining a function that will be called when your API is accessed. 

```
@app.route('/')
def hello_world():
    return {'message': 'Hello, World!'}
```
Explaining the above:
When a client (PostMan, browser, etc.) makes a GET request to the root endpoint (i.e "/") of the Flask app, the ``hello_world()`` function will be executed. Which returns a Python Dictionary with a single key "message" and value of ``Hello, World!``
```
{
    "message": "Hello, World!"
}
```
Once you understand the fundamentals of creating API requests, you can get pretty awesome JSON responses for yourself in the format shown below :) 
```
{
    "name": "Go Jonny Go Go Go",
    "age": old enough to be awesome,
    "email": "jonnybegood@example.com",
    "address": {
        "street": "123 Forest Ave",
        "city": "MyCity",
        "state": "MyState",
        "zip": "12345"
    }
}
```

I enjoy Python and most libraries and packages available. A short demonstration is in order using Python, the "Requests", the "JSON" module, and Yelps API. I'll provide each line with an explanation for folks who are curious about my flow. 

These modules are used to make the HTTP request and parse JSON responses as expected.

```
import requests
import json
``` 

The lines below are defining the Yelp endpoint and the parameters to include in the API request. 

```
url = "https://api.yelp.com/v3/business/search"
params = {
     "term": "restaurants",
     "location": "Chicago",
     "limit": 10

}
```
Setting your headers with the API_KEY generated from the app you've created within Yelp. For more information, check out this [link](https://docs.developer.yelp.com/docs/fusion-authentication).

```
headers = {
    "Authorization": "Bearer <API_KEY>"
}
```

I've created a ``response`` variable that stores the response from the API and will send a GET request to the Yelp API endpoint specified in the `URL`. We will include the API authorization header in `headers` and the search parameter in `params`.

```
response = requests.get(url, headers=headers, params=params)
```

Next, We will need to parse the JSON response returned by the API, which we know is stored in the ``response`` variable. We can use the ``json.loads()`` method and then store the result within the ``data`` variable.

```
data = json.loads(response.text)
```
With the data you've retrieved, you can extract the list of businesses from the JSON response data.

```
businesses = data["businesses"]
```

The final step would be to loop through the lists of businesses in the ``businesses`` variable, and for each business, it extracts the name and rating values, then prints them to your console for review.

```
for business in businesses:
    name = business["name"]
    rating = business["rating"]
    print(f"{name}: {rating}")

```

You should get back a response JSON like this:
```
{
  "businesses": [
    {
      "id": "hBb2RcUVumohfY2kbGKvKQ",
      "alias": "hide-seek-chicago",
      "name": "Hide+Seek",
      "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/lIX142MB4grB7gZs-plt_Q/o.jpg",
      "is_closed": false,
      "url": "https://www.yelp.com/biz/hide-seek-chicago?adjust_creative=3Q-VbeGWSe3kCIvZvn-AXg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_search&utm_source=3Q-VbeGWSe3kCIvZvn-AXg",
      "review_count": 79,
      "categories": [
        {
          "alias": "newamerican",
          "title": "American (New)"
        }
      ],
      "rating": 4,
      "coordinates": {
        "latitude": 41.88466,
        "longitude": -87.64899
      },
      "transactions": [],
      "location": {
        "address1": "838 W Randolph St",
        "address2": "",
        "address3": null,
        "city": "Chicago",
        "zip_code": "60607",
        "country": "US",
        "state": "IL",
        "display_address": [
          "838 W Randolph St",
          "Chicago, IL 60607"
        ]
      },
      "phone": "+13126808217",
      "display_phone": "(312) 680-8217",
      "distance": 8950.985739997868
    }
```

Now it's your turn! I encourage you to try out some of the APIs I've discussed in this article, and share your own experiences in the comments. Together, we can continue to learn and grow as developers.

Until next time - Cheers!

<img width="100%" style="width:100%" src="https://media.giphy.com/media/ui1hpJSyBDWlG/giphy.gif">