Let’s Start Python Programming For Beginners to Advanced. Working with APIs, Lectures 19
π Lecture 19: Working with APIs
π― Goal
By the end of this lecture, you will:
- Understand what an API is and why itβs useful.
- Know how to make HTTP requests in Python using the
requests
library. - Be able to get data from a real-world API (like weather or news).
- Build a simple weather checker or joke fetcher app.
π§ What Is an API?
An API (Application Programming Interface) is like a waiter between your program and another service (like a website or database).
You ask for something β like “What’s the weather today?” β and the API goes and gets the answer for you.
Real-Life Examples:
- Weather apps use weather APIs.
- News websites use news APIs.
- Games use leaderboard APIs to show scores.
π οΈ Setting Up β Install requests
Weβll use the requests
library to talk to APIs.
Install it using:
pip install requests
Then import it in your code:
import requests
π Making a GET Request
The most common way to get data from an API is using a GET request .
Example:
import requests
response = requests.get("https://api.quotable.io/random")
data = response.json()
print("Here's a random quote:")
print(f'"{data["content"]}" β {data["author"]}')
This gets a random quote from the Quotable API .
βοΈ Mini Project: Get the Current Weather
Letβs build a Weather Checker App using a free weather API.
π Sign up at weatherapi.com or openweathermap.org to get your free API key.
Code Example:
import requests
API_KEY = "your_api_key_here"
city = input("Enter city name: ")
url = f"http://api.weatherapi.com/v1/current.json?key={API_KEY}&q={city}"
response = requests.get(url)
data = response.json()
if "error" in data:
print("Error:", data["error"]["message"])
else:
temp = data["current"]["temp_c"]
condition = data["current"]["condition"][0]["text"]
print(f"The current temperature in {city} is {temp}Β°C and the weather is {condition}.")
π Sample Output:
Enter city name: London
The current temperature in London is 15Β°C and the weather is Partly cloudy.
π Fun Project: Fetch a Random Joke
Use the Joke API to get a joke:
import requests
response = requests.get("https://v2.jokeapi.dev/joke/Any")
data = response.json()
if data["type"] == "single":
print(data["joke"])
else:
print(data["setup"])
print("...", data["delivery"])
π‘ Understanding HTTP Status Codes
When you make a request, the server responds with a status code :
Code | Meaning |
---|---|
200 | OK β Everything worked β |
404 | Not Found β The URL was wrong β |
401 | Unauthorized β You need an API key β |
500 | Server Error β Something went wrong on their side π¨ |
Check the status code before processing data:
if response.status_code == 200:
data = response.json()
else:
print("Failed to get data.")

π§ͺ Try It Yourself!
Try building one of these:
- A quote generator that gives a new quote every time.
- A random dog image viewer using https://dog.ceo/dog-api/
- A fun fact generator using https://uselessfacts.jsph.pl/
π Challenge (Optional)
Make a News Headlines Reader using a news API like:
Example:
API_KEY = "your_news_api_key"
url = f"https://gnews.io/api/v4/top-headlines?token={API_KEY}&lang=en"
response = requests.get(url)
data = response.json()
for article in data["articles"]:
print("π°", article["title"])
print("π", article["url"], "\n")v
π§ Kids Corner
π§ Imagine your robot friend can call up other robot friends and ask them questions, like βWhatβs the weather today?β or βTell me a joke!β
π€ Robot says:
Iβm talking to my robot friends over the internet now!
π Summary
- An API lets your program talk to another service.
- Use the
requests
library to send HTTP requests. - Most APIs return data in JSON format.
- You can build fun tools like weather apps, joke fetchers, and news readers.
- Always check the status code to know if your request worked.
Stay Updated
If you found this information useful, donβt forget to bookmark this page and Share and leave your feedback in the comment section below