← Back
Working with APIs in Python
Learn how to connect to online services and fetch live data using Python APIs. Perfect for beginners!
What is an API?
An API (Application Programming Interface) lets different programs talk to each other. Think of it like a waiter taking your order to the kitchen and bringing back your food.
Making Your First API Request
Let's get weather data using Python:
import requests
# Get weather data (free API)
response = requests.get('https://api.weatherapi.com/v1/current.json?key=YOUR_KEY&q=London')
data = response.json()
print(f"Temperature: {data['current']['temp_c']}°C")
print(f"Condition: {data['current']['condition']['text']}")
Popular Free APIs to Try
- OpenWeatherMap: Get weather data for any city
- REST Countries: Information about any country
- JSONPlaceholder: Fake data for testing
- NASA API: Space photos and data
Handling JSON Data
Most APIs return data in JSON format. Here's how to work with it:
import requests
response = requests.get('https://api.github.com/users/octocat')
user_data = response.json()
print(f"Username: {user_data['login']}")
print(f"Bio: {user_data['bio']}")
print(f"Public Repos: {user_data['public_repos']}")
💡 Pro Tip: Always check if the API request was successful using response.status_code before processing data!
Sending Data to APIs
You can also send data to APIs (POST requests):
import requests
data = {
'title': 'My Post',
'body': 'This is my first API post!',
'userId': 1
}
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=data)
print(response.json())
Best Practices
- Store API keys securely (never share them!)
- Check API rate limits to avoid being blocked
- Handle errors gracefully
- Cache data when possible to reduce API calls
← Back to Blog