Working with Web APIs
๐ What is a Web API?
A Web API (Application Programming Interface) allows your application to interact with external services and fetch live data. Python makes this easy using the requests library and JSON.
๐ฆ Install Requests
# If not installed already:
pip install requests
๐ก Example: Fetch GitHub Profile
This script uses GitHub’s public API to fetch user info:
import requests
username = "torvalds"
url = f"https://api.github.com/users/{username}"
response = requests.get(url)
data = response.json()
print(f"Name: {data['name']}")
print(f"Repos: {data['public_repos']}")
print(f"Followers: {data['followers']}")
๐ง Explanation
requests.get()makes an HTTP GET request.json()converts the response to a Python dictionary- You can extract values using keys like
data['name']
๐ Challenge: Get Weather with OpenWeatherMap
import requests
api_key = "YOUR_API_KEY"
city = "London"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
response = requests.get(url)
data = response.json()
print(f"{city} Temperature: {data['main']['temp']} °C")
Sign up at openweathermap.org/api to get a free API key.
๐ Summary
- ✅ Web APIs provide real-time data to your Python apps
- ๐ฆ Use
requeststo make API calls - ๐งพ Parse responses using
.json() - ๐ Some APIs need API keys—store them safely
Comments
Post a Comment