Working with Web APIs

Working with Web APIs | Python Tutorial

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 requests to make API calls
  • ๐Ÿงพ Parse responses using .json()
  • ๐Ÿ” Some APIs need API keys—store them safely

Comments