🐍 Lesson 28: Python APIs – Sending Requests & Handling JSON Data

Welcome to Lesson 28! Today you’ll learn how to interact with APIs using Python. APIs let your program communicate with external services like weather apps, ChatGPT, YouTube, payment gateways, maps, and more. This lesson will teach you how to fetch, send, and handle data from APIs effectively.


💡 Quick Benefits of Learning APIs

  • Communicate with external services like weather, payment systems, and more
  • Automate data collection and communication with other applications
  • Essential for web development, machine learning, and backend services
  • Critical skill for modern developers working with AI, data science, and cloud computing

🌐 What Is an API?

API stands for Application Programming Interface. It allows two applications to talk to each other and exchange data seamlessly.

Examples:

  • Get weather data
  • Fetch cryptocurrency prices
  • Search YouTube videos
  • Send messages via WhatsApp API
  • Connect to AI models or databases

📦 1. Installing Dependencies


pip install requests

We’ll use the requests library to send HTTP requests and handle API responses in Python.


📦 2. Sending a GET Request

GET requests are used to fetch data from an API. Let’s send a request to a test API and print the result:


import requests

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

print(response.status_code)
print(response.json())  # Convert JSON to Python dict

Here, we fetch data from a sample API and convert the JSON response to a Python dictionary.


📦 3. Accessing JSON Fields


data = response.json()

print("Title:", data["title"])
print("User ID:", data["userId"])

You can access specific fields in the returned JSON data by using the keys, just like any dictionary in Python.


📦 4. Sending a POST Request

POST requests are used to send data to a server. Here’s how to send a POST request with JSON data:


payload = {
    "title": "New Post",
    "body": "Learning Python APIs!",
    "userId": 1
}

response = requests.post(
    "https://jsonplaceholder.typicode.com/posts",
    json=payload
)

print(response.status_code)
print(response.json())

We’re sending new data to the server in JSON format using the requests.post method.


📦 5. Adding Headers (e.g., API Keys)

To authenticate or provide additional information to the API, you can add headers such as API keys:


headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

response = requests.get("https://api.example.com/data", headers=headers)

Headers are essential for security and handling authentication when making requests to certain APIs.


📦 6. Error Handling

It's important to handle potential errors when making requests, such as network issues or bad responses. Here's an example of how to handle errors properly:


try:
    r = requests.get("https://api.example.com/data")
    r.raise_for_status()  # Raises error for bad responses
    print(r.json())
except requests.exceptions.HTTPError as e:
    print("HTTP Error:", e)

Using raise_for_status() ensures that HTTP errors are caught and handled gracefully.


🧠 Why Learning APIs Is Important

  • Essential for backend and full-stack development
  • Widely used in automation, machine learning, and mobile apps
  • Enables data-driven applications that connect to live data
  • Lets your apps communicate with third-party services for added functionality

🧪 Practice

  1. Fetch and print the title of a post from the JSONPlaceholder API.
  2. Send a POST request with custom data.
  3. Use an API that returns weather information and display the forecast.
  4. Handle errors using try and except while calling an API.

❓ Common Mistakes

  • Not handling errors correctly (e.g., HTTP errors, invalid responses)
  • Forgetting to pass API keys or authentication tokens in headers
  • Not checking the API documentation for rate limits or usage restrictions

❓ Frequently Asked Questions (FAQ)

1. How do I get an API key?

API keys are usually provided by the service you are interacting with. You can typically get them by registering on the service's developer portal.

2. What should I do if the API doesn't work?

Check the API documentation for troubleshooting tips. Ensure you have the correct endpoint and parameters, and verify that your API key is valid.

3. Can I use APIs for free?

Many APIs offer free tiers with limited access. Be sure to check the pricing and limitations before using an API extensively.


🚀 What’s Next?

In the next lesson, you’ll learn how to:

  • Use web scraping techniques to extract data from websites
  • Handle HTTP requests efficiently
  • Work with real-time data from online sources

➡ Next Lesson

Go to Lesson 29 →

Comments

Popular posts from this blog

How to Install Geany 2.1 on Windows 10/11 (2026) | Step-by-Step Guide

How to Uninstall Bluefish 2.2.19 on Windows 10/11 (2026) | Step-by-Step Guide

How to Install Visual Studio 2026 on Windows 10/11 | Step-by-Step Guide