Saturday, December 1, 2018

Learn Python and APIs with Open Weather Map in 5 Mins

My motivation for this post is to show how easy it is to start programming. Too many people are mystified by what programmers do, when in reality anyone can learn a little programming and automate simple tasks in their lives.

Here I use Open Weather Map to get weather data for a list of US cities. I use Python since it is one of the most readable and easiest languages to get started with, and I use the library 'requests' to simplify getting data from an API. The whole code is about 20 lines including comments, and you can run it yourself here without downloading anything! Here is the full code if you just want to jump in:





Topics: Python, APIs, HTTP Requests, Arrays, For Loops, Conditionals, and More!
Python
I love Python for its simplicity and readability, which helps when I need to quickly put together a prototype. Many other languages, like Java, C++, Node.js, etc. are more verbose and so can often take longer to write and understand. While these other languages have their own benefits, Python is very powerful and a great starting point for non-developers. Whether you want to do data analysis, machine learning, or web backends, Python is a great tool.



APIs
API stands for Application Programming Interface, which is just nerd talk for "a simple way to communicate with a server." Its the building block or backbone for most of modern programming. Want to add Google Maps to your site? Use Google's API. Want to build a Bitcoin wallet app? Try Blockchain's API. Want to build an automated email campaign? Check out Sendgrid's API. Want to build an object tracking computer vision app? Check out OpenCV. Want to build a machine learning app? Try Tensorflow's API. Want to creep on your friends? Just use Facebook's API.

The documentation is usually all you need.

Want to get stock price data? Try Intrinio's API. Want to track the number of clicks a link gets? Check out Bit.ly's API. Want to make a bid on eBay within seconds? Check out their API. I could go on and on and on, but I'm just as annoyed as you are.



HTTP Requests
Most APIs require making an HTTP request over the internet. In Python, you can use a simple library called requests. A library is just someone else's code that makes your life simpler. Instead of having to write the code yourself, someone else took hundreds of lines of code and allow you to only need to run one line. This is part of why it is infinitely easier to code in 2018 than in 1998. At the top of your code in Python you "import" libraries that you plan to use. Many APIs return the data in JSON format, which looks like this: "name":"Pepito""age":30"car":null }

In our case, the HTTP Link we want to use is Open Weather Map's. The base link is http://api.openweathermap.org/data/2.5/ We can add what are called parameters to specify what kind of data we want to request. Open Weather Map's API has a ton of options. We will use 'weather' to get the current weather data, as opposed to 'forecast' for the 5 hour prediction.

API Key Security
For every API you use, you will need an API key, which is basically your unique password. In general, you should never share your API key with anyone. Once a developer accidentally shared my Google Cloud Key on a public Github Repository, and someone proceeded to use my key for mining cryptocurrency. Fortunately, Google detected and reimbursed my mistake within 24 hours; otherwise I would have been charged $300 for cloud usage. Accidentally sharing API keys is also how a hacker store 50 million user's data from Uber! Additionally, you should try not to store API keys in plain text, but instead use environment variables. That's beyond the scope of this post, but if you are working in an security intensive application, make sure to read a lot more and consult with experts. In this case, I am using a free API key that limits 60 requests per second, and I am trying to avoid you needing to create an account, so hopefully no one abuses this key. If they do though, I will have to remove my key and replace it with "putYourAPIKeyHere."

Logic: Variables, Arrays, For Loops, and Conditionals
If you just learn these simple concepts, you will be well on the way to learning programming. A variable allows you to store the same word, integer, or other information to be used later in your program. For example, we use weather = r['weather'] to store the responses' weather attribute and later print it out. Printing is what spits stuff out in the console for you to read. We also use variables to adapt the HTTP Link we want to call

httpLink = 'http://api.openweathermap.org/data/2.5/'+ parameter+'?q=' + city +',us&appid=' + owm_api_key

Arrays are the basically multiple variables- they allow you to store infinite information in any format. We use cities = ['New York', 'Denver', 'Atlanta'] to store an array with the cities we want to analyze. This leads to the concept of 'for loops.' For loops are used if we want to iterate (or go one by one) through an array in order to execute a specific piece of logic for each input. In our case, we want to make a weather request for each city in our array. Finally, just to show the concept of conditionals, or if statements, I add a print statement if city == 'Denver'

From each of these concepts, you can start to build apps. Web APIs allow you to build off of other companies' libraries, Python makes it easy to start programming, and learning a little logic guides your intuition as a programmer. No doubt, there is much more to learn to be a great programmer, but this just shows that in a very short period of time you can learn how to program and build off existing concepts. 





5 comments:

  1. I've actually used open weather api in a class assignment and it was relatively easy to handle even though I'm a starter with python. I was able to use it to find out the live weather situations in places around the world!

    ReplyDelete
  2. Here's a suggestion for your next topic: Learn OOP with Python.

    ReplyDelete
    Replies
    1. Thanks for your comment! Any particular suggestions, or just in general?

      Delete
    2. One needs to learn how to use a framework and its' associated ecosystem to become a better developer. Basic articles are good (dime a dozen on the internet about loops and variables and APIs) but time to get serious!

      Delete
    3. Yeah, this is true. I didn't clarify too much on my motivations- I'm not necessarily trying to start a coding tutorial blog, although I will add some more advanced content eventually. More trying to show some of my friends how easy it is to get started. Also, I don't have too much of an academic background in coding- more practical, so trying to emphasize that aspect of my experience. Check out some of my other posts (more coming soon!) Thanks again

      Delete