Lesson 16: Introduction to APIs and HTTP Requests

How Python communicates with web services and retrieves online data

What Is an API?

An API (Application Programming Interface) allows different software systems to communicate. Web APIs let your Python programs interact with online services such as weather data, maps, social media, or databases.

What Are HTTP Requests?

HTTP (Hypertext Transfer Protocol) is the foundation of communication on the web. When your program interacts with an API, it sends HTTP requests and receives responses.

Common HTTP Methods

Using the requests Library

The requests library makes HTTP communication simple and readable.

Installing requests

pip install requests

Making a GET Request

import requests

response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())

Understanding API Responses

Most APIs return data in JSON format. You can convert it to Python objects using .json():

data = response.json()
print(data["current_user_url"])

Query Parameters

Many APIs accept parameters to filter or customize results:

params = {"q": "python", "sort": "stars"}
response = requests.get("https://api.github.com/search/repositories", params=params)
print(response.json())

Handling Errors

Always check for errors when calling APIs:

if response.status_code == 200:
    print("Success!")
else:
    print("Error:", response.status_code)

Using API Keys

Some APIs require authentication using an API key. Never hard‑code keys in public code.

headers = {"Authorization": "Bearer YOUR_API_KEY"}
response = requests.get("https://api.example.com/data", headers=headers)

Why APIs Matter

Next Steps

Now that you understand APIs and HTTP requests, you're ready to explore how to work with JSON data in Lesson 17: Working with JSON Data.

← Back to Lesson Index