Skip to content

Python! Working with APIs | Lectures 19

Lecture 19 Working with APIs

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 :

CodeMeaning
200OK – Everything worked βœ…
404Not Found – The URL was wrong ❌
401Unauthorized – You need an API key ❗
500Server 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.")
Lecture 19 Working with APIs
Lecture 19 Working with APIs

πŸ§ͺ Try It Yourself!

Try building one of these:

  1. A quote generator that gives a new quote every time.
  2. A random dog image viewer using https://dog.ceo/dog-api/
  3. 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

Python! Pet Simulator Game | Lectures 18

Najeeb Alam

Najeeb Alam

Technical writer specializes in developer, Blogging and Online Journalism. I have been working in this field for the last 20 years.

Leave a Reply

Your email address will not be published. Required fields are marked *