🌐 How to Use APIs in Python — A Beginner’s Guide
💡 Connect Your Code with the Real World

🪄 Introduction
When I first learned Python, most of my programs worked in isolation — calculators, ATM systems, to-do lists… all self-contained. But soon, I realized:
Real-world apps don’t live alone — they talk to other apps!
That’s where APIs (Application Programming Interfaces) come in.
APIs allow your code to fetch live data, like weather updates, stock prices, news headlines, or even your favorite songs on Spotify.
If you’ve ever used Google Maps, Instagram, or ChatGPT — you’ve already interacted with APIs (without realizing it 😄).
💭 What Exactly Is an API?
In simple words —
An API is like a waiter in a restaurant.
You tell the waiter (API) what you want (request),
and the waiter brings your order from the kitchen (server) and hands it to you (response).
Your program → API → Server → API → Your program again.
That’s it — magic in motion ✨
⚙️ Step 1: Setting Up
Let’s start with the basics.
You’ll need the requests library — one of the most popular Python libraries to work with APIs.
If it’s not installed, just run:
pip install requests
Now import it in your Python script:
import requests
☁️ Step 2: Choose an API (Example: OpenWeatherMap)
Let’s use a free weather API to fetch live weather data.
Go to https://openweathermap.org/api
Sign up, and you’ll get a free API key (a unique code that identifies you).
You can now make requests like this:
https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_API_KEY
🧠 Step 3: Writing the Python Code
Here’s a simple Python program to fetch live weather info:
import requests
# Replace with your API key
API_KEY = "your_api_key_here"
city = input("Enter city name: ")
# API URL
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
# Send request
response = requests.get(url)
# Convert response to JSON
data = response.json()
if data["cod"] == 200:
main = data["main"]
weather = data["weather"][0]["description"]
temp = main["temp"]
humidity = main["humidity"]
print(f"\nWeather in {city}: {weather}")
print(f"Temperature: {temp}°C")
print(f"Humidity: {humidity}%")
else:
print("❌ City not found or API error!")
🔍 Step 4: Understanding the Code
requests.get()→ sends a request to the API..json()→ converts the response into a Python dictionary.We access fields like
data["main"]["temp"]to get specific values.
The API gives a JSON response like this:
{
"weather": [{"description": "clear sky"}],
"main": {"temp": 27.5, "humidity": 60}
}
So, your Python code just reads and prints the parts you need.
🧩 Step 5: Making It More Interactive
Try adding:
✅ Error handling (for wrong city names)
✅ Colored output using the colorama library
✅ Options to display temperature in °C or °F
✅ Multiple city lookups
Here’s an improved snippet:
import requests
API_KEY = "your_api_key_here"
def get_weather(city):
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={API_KEY}&units=metric"
response = requests.get(url)
return response.json()
while True:
city = input("\nEnter city name (or 'exit' to quit): ")
if city.lower() == 'exit':
print("Goodbye 👋")
break
data = get_weather(city)
if data["cod"] == 200:
weather = data["weather"][0]["description"]
temp = data["main"]["temp"]
print(f"🌤️ {city.title()}: {weather}, {temp}°C")
else:
print("❌ City not found. Try again!")
🌍 Step 6: What You Just Learned
By now, you’ve learned how to:
✅ Understand APIs and their purpose
✅ Send HTTP requests in Python
✅ Parse and display JSON data
✅ Build an interactive app using real-world data
This is the same foundation used in web apps, chatbots, and even AI tools!
💬 Why APIs Matter for You as a Student
Building with APIs is like giving your program superpowers.
It turns your static code into something alive — connected to the internet, pulling live data, and interacting dynamically.
Once you understand APIs, you can explore endless projects:
🔎 Weather App
📰 News Headlines App
💸 Currency Converter
🎵 Spotify Playlist Fetcher
🧠 Chatbot using OpenAI API
✨ Final Thoughts
When I first fetched live weather data, it genuinely felt like magic — my code was talking to the internet!
That’s the power of APIs.
They’re not just tools; they’re bridges connecting your logic to the world’s data.
So next time you build something, don’t keep it isolated — connect it.
Because in tech, connection = innovation. 🌍💻
🏷️ Key Takeaways
APIs let apps communicate and share data.
Python’s
requestsmodule makes it super easy.JSON is your new best friend.
You don’t need advanced knowledge — just curiosity.
🧑💻 Author
Written by [Divyanshi] — a B.Tech student who loves turning small coding ideas into real-world solutions and sharing them through simple, human-friendly blogs.