Building a Weather App
Using fetch functions with public APIs
When planning this app, I started searching for public APIs that dealt with weather. One that seemed to work well was called 7Timer! and it had very clear documentation on how to make a request and how to interpret the results it gave back. However I quickly ran into my first major obstacle- when making the request, you needed to provide the location as latitude and longitude coordinates. Other weather APIs I found also seemed to have the same requirement. This was an issue because most humans do not know the latitude and longitude coordinates of locations offhand.
After thinking about different possible solutions on how to get around this, I discovered a second API called Geocode.xyz which could take a request including latitude and longitude coordinates and respond with a location…or take a location and give back latitude and longitude coordinates! This was exactly what I needed. Armed with both of these APIs and having tested that each one worked as I expected to independently, it was time to combine them together so that a user could enter a location in the text field and receive the weather as a result. Let’s take a look at how this should work.
So now that we know how the program should function, how do we implement this in code? I did this by nesting one fetch method inside another. Let’s take a look at the following code.
If you copy this code you can run the program yourself and see the results. Try changing the userInput value on line 1 to “Houston, TX” or “Baltimore, MD” instead and see what you get.
APIs are powerful tools that allow you to include all kinds of data and features in your applications. There are tons of public APIs that anyone can use covering almost any topic you can think of. I used two different ones to make a weather app but if you want data on the stock market, current events and news, or even just random Harry Potter facts, there’s an API for you out there. After picking one that interests you, it is just a matter of looking at the documentation to understand how to make a request and understand the response it sends back, and combining it with the fetch method to start building some seriously fun and interesting projects.