Lesson 27: API Requests in Python

๐ŸŽฏ Lesson Objective

To learn how to interact with APIs using Python, send requests, handle responses, and work with data from external sources such as web services or third-party platforms.


๐Ÿงฉ 1. What Is an API?

API (Application Programming Interface) allows one program to communicate with another.

  • APIs are commonly used to fetch data from web services, interact with databases, or control external applications.
  • HTTP methods are mostly used:
    • GET โ†’ Retrieve data
    • POST โ†’ Send data
    • PUT โ†’ Update data
    • DELETE โ†’ Delete data

โš™๏ธ 2. Python Requests Module

The requests module is the most popular library for working with HTTP APIs in Python.

โœ… Install if not already installed:

pip install requests

Import the module:

import requests

๐Ÿ”น 3. Sending a GET Request

GET requests are used to retrieve data from a server.

import requests

url = "https://jsonplaceholder.typicode.com/posts/1"
response = requests.get(url)

# Check response status
print("Status Code:", response.status_code)

# Get JSON data
data = response.json()
print(data)

Output Example:

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati",
  "body": "quia et suscipit..."
}

๐Ÿ”น 4. Sending a POST Request

POST requests send data to the server.

url = "https://jsonplaceholder.typicode.com/posts"
payload = {
    "title": "Python API",
    "body": "This is a test post",
    "userId": 1
}

response = requests.post(url, json=payload)
print("Status Code:", response.status_code)
print(response.json())

Output Example:

{
  "title": "Python API",
  "body": "This is a test post",
  "userId": 1,
  "id": 101
}

๐Ÿ”น 5. Adding Headers

Sometimes APIs require headers for authentication or content type.

url = "https://jsonplaceholder.typicode.com/posts"
headers = {"Content-Type": "application/json"}

response = requests.get(url, headers=headers)
print(response.json()[0])

๐Ÿ”น 6. Handling Query Parameters

Many APIs accept query parameters to filter or sort data.

url = "https://jsonplaceholder.typicode.com/posts"
params = {"userId": 1}

response = requests.get(url, params=params)
posts = response.json()

for post in posts:
    print(f"{post['id']}: {post['title']}")

๐Ÿ”น 7. Error Handling in API Requests

Always handle errors like network failures or invalid responses.

try:
    response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
    response.raise_for_status()  # Raises HTTPError for bad responses
    data = response.json()
    print(data)
except requests.exceptions.HTTPError as err:
    print("HTTP error occurred:", err)
except requests.exceptions.ConnectionError as err:
    print("Connection error occurred:", err)
except requests.exceptions.Timeout as err:
    print("Request timed out:", err)
except requests.exceptions.RequestException as err:
    print("An error occurred:", err)

๐Ÿ”น 8. Working with JSON Data

API responses are usually JSON, so you can manipulate them as dictionaries or lists.

import requests

url = "https://jsonplaceholder.typicode.com/users"
response = requests.get(url)
users = response.json()

for user in users:
    print(f"Name: {user['name']}, Email: {user['email']}, City: {user['address']['city']}")

Output Example:

Name: Leanne Graham, Email: Sincere@april.biz, City: Gwenborough
Name: Ervin Howell, Email: Shanna@melissa.tv, City: Wisokyburgh
...

๐Ÿ”น 9. Real-Life Example โ€“ Weather API

Fetching weather data from OpenWeatherMap API.

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()

if response.status_code == 200:
    print(f"City: {data['name']}")
    print(f"Temperature: {data['main']['temp']}ยฐC")
    print(f"Weather: {data['weather'][0]['description']}")
else:
    print("Error:", data["message"])

Output Example:

City: London
Temperature: 18ยฐC
Weather: light rain

๐Ÿ”น 10. Authentication with APIs

Some APIs require authentication, e.g., API keys, tokens, or OAuth.

url = "https://api.example.com/data"
headers = {"Authorization": "Bearer YOUR_ACCESS_TOKEN"}

response = requests.get(url, headers=headers)
print(response.json())

๐Ÿ”น 11. Advanced Techniques

  • Timeouts: Avoid waiting forever for a server response.
requests.get(url, timeout=5)  # 5 seconds max
  • Retrying Failed Requests: Use requests.adapters for automatic retries.
  • Streaming Large Data: Use stream=True for big files to avoid memory overload.
with requests.get("https://example.com/largefile", stream=True) as r:
    with open("largefile.zip", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            f.write(chunk)


Comments

Leave a Reply

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