Hello, young web explorer! You now know how to use sockets to send messages over a network. But did you know that most applications on the internet use a special protocol called HTTP? It's the language that web browsers and servers speak.
Have you ever opened a web browser, typed a website name, and seen a page appear? That's HTTP in action. HTTP stands for HyperText Transfer Protocol โ it's the set of rules that web browsers and servers use to talk to each other.
In this module, we will learn about HTTP, how web browsers make requests, and how servers respond. We will also learn about APIs (Application Programming Interfaces) โ the way applications talk to each other. You will use Python's requests library to make web requests and work with real-world APIs.
By the end of this module, you will be able to write Python programs that can get information from the web, send data to servers, and even build simple web applications.
After reading this module, you will be able to:
requests library to make HTTP requests.In a bustling city called Websville, there was a restaurant called The API Cafe. The restaurant had a special menu. But you couldn't just walk in and order โ you had to send a request in a specific format.
The restaurant had a chef (the server) who received requests and sent back responses. The format was always the same: you asked for something (request), and the chef gave you what you wanted (response) with a status code (like "200 OK" or "404 Not Found").
One day, a young Python coder named Pip wanted to get the weather from the restaurant. She sent a request: "GET /weather" and the chef responded with "Sunny, 25ยฐC". Pip could do this from any computer, anywhere!
This is exactly how HTTP works โ you send a request to a server, and it sends back a response. APIs are like the menu โ they tell you what you can ask for and what you will get.
Definition: HTTP stands for HyperText Transfer Protocol. It is the set of rules for sending and receiving web pages and data over the internet.
Why it is important: Every time you visit a website, your browser uses HTTP to talk to the web server.
Simple explanation: Like a waiter taking your order (request) and bringing you your food (response).
Real-life example: When you type "google.com" in your browser, your browser sends an HTTP request to Google's server.
School example: The school's website uses HTTP to show information to students.
Home example: When you search for a video on YouTube, HTTP is used.
Nigerian example: When you visit a Nigerian news website, your browser uses HTTP.
Browser (Client) ---- HTTP Request ----> Web Server
Browser (Client) <--- HTTP Response ---- Web Server
Mini summary: HTTP is the language that web browsers and servers use to talk.
Definition: An HTTP request is a message that a client (like a browser) sends to a server to ask for something.
Why it is important: It tells the server what the client wants.
Simple explanation: Like ordering a pizza โ you tell the pizza place what you want.
Parts of an HTTP request:
GET /weather HTTP/1.1
Host: api.weather.com
User-Agent: Python/3.9
Mini summary: An HTTP request asks a server for something.
Definition: An HTTP response is the message that a server sends back to the client.
Why it is important: It contains the data the client asked for.
Simple explanation: Like the pizza place giving you your pizza.
Parts of an HTTP response:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1234
<html><body>Hello, world!</body></html>
Mini summary: An HTTP response is the server's answer to a request.
Definition: HTTP methods tell the server what action to perform.
Why it is important: Different actions need different methods.
Common methods:
| Method | Use | Example |
|---|---|---|
| GET | Retrieve data | Getting a web page |
| POST | Send new data | Submitting a form |
| PUT | Update data | Updating a profile |
| DELETE | Remove data | Deleting a file |
Mini summary: HTTP methods tell the server what to do.
Definition: Status codes are numbers that tell you the result of your request.
Why it is important: They tell you if your request worked or what went wrong.
Common status codes:
200 OK โ "Everything is fine!"
404 Not Found โ "What you asked for doesn't exist."
500 Internal Server Error โ "The server made a mistake."
Mini summary: Status codes tell you if your request worked or failed.
Definition: API stands for Application Programming Interface. It's a set of rules that allows one program to talk to another.
Why it is important: APIs let your program use data and services from other programs.
Simple explanation: Like a menu at a restaurant โ it tells you what you can order and how to order it.
Real-life example: The Google Maps API lets you add maps to your app.
School example: The school's system might have an API to get student schedules.
Home example: A weather app uses a weather API to get the forecast.
Nigerian example: A Nigerian fintech company uses a payment API to process transactions.
Your Program ---- API Request ----> [ API ] ----> Data Provider
Your Program <-- API Response ---- [ API ] <---- Data Provider
Mini summary: An API is a way for programs to talk to each other.
Definition: REST stands for Representational State Transfer. RESTful APIs are APIs that follow a set of principles for web communication.
Why it is important: Most modern web APIs are RESTful.
Simple explanation: Like a set of house rules for how to ask for things over the internet.
Key principles:
GET /users โ Get all users
GET /users/1 โ Get user with ID 1
POST /users โ Create a new user
PUT /users/1 โ Update user with ID 1
DELETE /users/1 โ Delete user with ID 1
Mini summary: RESTful APIs are APIs that follow a standard way of working.
Definition: JSON stands for JavaScript Object Notation. It is a way to represent data as key-value pairs.
Why it is important: Most APIs return data in JSON format.
Simple explanation: Like a dictionary that has labels and values.
Real-life example: A weather API might return: {"city": "Lagos", "temperature": 30}.
School example: A school API might return student data in JSON.
Home example: A smart home API returns device status in JSON.
Nigerian example: A Nigerian bank API returns transaction data in JSON.
{
"name": "Tolu",
"age": 25,
"city": "Lagos"
}
Mini summary: JSON is the format that APIs use to send data.
Definition: The requests library is a Python package that makes it easy to send HTTP requests.
Why it is important: It's much simpler than using sockets for HTTP.
Simple explanation: Like a remote control that lets you send commands to a server.
Real-life example: You use requests.get() to get data from an API.
School example: Students use requests to get data for projects.
Home example: A Python script uses requests to check the weather.
Nigerian example: A developer uses requests to connect to a payment API.
import requests
response = requests.get('https://api.example.com/data')
print(response.status_code) # 200
print(response.json()) # Data as JSON
Mini summary: The requests library makes HTTP requests easy.
Definition: A GET request is used to retrieve data from a server.
Why it is important: This is how you get information from APIs.
Simple explanation: Like asking a librarian for a book.
Real-life example: Getting the latest news from a news API.
School example: Getting the school's event calendar.
Home example: Getting the weather forecast.
Nigerian example: Getting the latest exchange rate from a financial API.
import requests
response = requests.get('https://api.weather.com/forecast')
data = response.json()
print(data)
Mini summary: GET requests retrieve data from a server.
Definition: A POST request is used to send data to a server.
Why it is important: This is how you create new data on a server.
Simple explanation: Like filling out a form and submitting it.
Real-life example: Creating a new user account.
School example: Submitting homework to a school system.
Home example: Sending a message in a chat app.
Nigerian example: Making a payment using a payment API.
import requests
data = {'name': 'Tolu', 'age': 25}
response = requests.post('https://api.example.com/users', json=data)
print(response.status_code) # 201 Created
Mini summary: POST requests send data to a server.
Definition: After making a request, you need to check the status code and parse the data.
Why it is important: You need to know if your request worked and what data you got.
Simple explanation: Like checking if your package arrived and what's inside.
Real-life example: Checking if an API returned a 200 OK before using the data.
School example: Checking if the school API returned student data.
Home example: Checking if the weather API returned the forecast.
Nigerian example: Checking if a payment API returned a success message.
import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
data = response.json()
print("Data:", data)
else:
print("Error:", response.status_code)
Mini summary: Always check the status code and handle the response.
Definition: Query parameters are key-value pairs that you add to a URL to send extra information.
Why it is important: They let you filter or customize your request.
Simple explanation: Like asking for a "large" pizza instead of a "small" one.
Real-life example: ?city=Lagos&units=metric to get weather for Lagos.
School example: ?grade=5 to get data for grade 5 students.
Home example: ?date=2025-06-01 to get events on a specific date.
Nigerian example: ?currency=NGN to get exchange rates for Naira.
import requests
params = {'city': 'Lagos', 'units': 'metric'}
response = requests.get('https://api.weather.com', params=params)
print(response.url) # https://api.weather.com?city=Lagos&units=metric
Mini summary: Query parameters add extra information to your request.
Definition: Headers are key-value pairs that provide metadata about the request. Authentication is how you prove you are allowed to use an API.
Why it is important: Many APIs require authentication to use them.
Simple explanation: Like showing your ID card to enter a building.
Real-life example: Using an API key in the headers.
School example: Using a student ID to access the school portal.
Home example: Using a token to access a smart home API.
Nigerian example: A bank uses an API key to authenticate transactions.
import requests
headers = {'Authorization': 'Bearer your_api_key'}
response = requests.get('https://api.example.com/data', headers=headers)
Mini summary: Headers and authentication are used to secure API requests.
Definition: An API client is a program that interacts with an API.
Why it is important: It allows you to automate tasks and get data programmatically.
Simple explanation: Like building a robot that talks to the API for you.
Real-life example: A program that checks the weather every hour.
School example: A program that gets the school's news feed.
Home example: A program that controls your smart lights.
Nigerian example: A program that checks Naira exchange rates.
import requests
def get_weather(city):
url = f'https://api.weather.com/forecast?city={city}'
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return None
weather = get_weather('Lagos')
print(weather)
Mini summary: An API client is a program that works with an API.
requests library if not already installed.Teachers, this module is very practical. Use live examples with public APIs (like weather or Pokemon). Show students how to use requests. Encourage them to explore APIs they find interesting. Emphasize the importance of checking status codes and handling errors. This module connects Python programming to real-world data.
Parents, help your child find fun APIs to explore โ like a joke API, a weather API, or a trivia API. Show them how to get data from the internet using Python. This is a great way to connect programming to real life. Encourage them to build small projects that use APIs.
requests library is one of the most popular Python libraries.requests library makes HTTP easy in Python.response.json().try/except for error handling.
+--------+ +---------+ +--------+
| Client |---->| HTTP |---->| Server |
| (Your | | Request | | |
| code) | | | | |
+--------+ +---------+ +--------+
| |
| |
| +---------+ |
+---->| HTTP |<-------------+
| Response|
+---------+
+--------+ +---------+ +--------+ +---------+
| Client |---->| API |---->| Server |---->| Database|
| | | Request | | | | |
+--------+ +---------+ +--------+ +---------+
| | | |
| | | |
| +---------+ +--------+ +---------+
+---->| API |<----| Server |<----| Database|
| Response| | | | |
+---------+ +--------+ +---------+
{
"name": "Tolu",
"age": 25,
"city": "Lagos",
"hobbies": ["reading", "coding", "gaming"]
}
| Feature | GET | POST |
|---|---|---|
| Purpose | Retrieve data | Send data |
| Data in URL? | Yes | No (in body) |
| Length limit | Limited | Large |
| Example | Searching for a page | Submitting a form |
| Category | Range | Meaning |
|---|---|---|
| 1xx | 100-199 | Information |
| 2xx | 200-299 | Success |
| 3xx | 300-399 | Redirection |
| 4xx | 400-499 | Client error |
| 5xx | 500-599 | Server error |
Excellent work! You have completed Module 3: HTTP and Working with APIs.
You learned about HTTP โ the language of the web. You understand requests and responses, methods (GET, POST, etc.), and status codes (200, 404, etc.).
You discovered what an API is and how to use RESTful APIs. You learned about JSON, the common data format for APIs. You used Python's requests library to make GET and POST requests, handle responses, add query parameters, and use authentication.
You now have the skills to connect your Python programs to the internet and use real-world data. In Module 4, we will learn about Network Automation โ Using Python to Manage Network Devices.
requests.get() and requests.post().Match the term on the left with the correct definition on the right.
| Term | Definition |
|---|---|
| 1. GET | A. Send data |
| 2. POST | B. Retrieve data |
| 3. 200 | C. Not Found |
| 4. 404 | D. Success |
| 5. API | E. Program communication |
Answers: 1-B, 2-A, 3-D, 4-C, 5-E
Scenario 1: You want to build a weather app. You find a weather API. What steps would you take to get weather data for Lagos?
Scenario 2: You are building a payment system for a Nigerian company. You decide to use a payment API. How would you send payment data securely?
Scenario 3: You make a request to an API and get a 404 response. What does this mean and what should you do?
Build a Fun API Client: In groups, find a public API (like a joke API, trivia API, or Pokemon API). Build a Python program that makes a request and displays the data in a fun way. Present your program to the class.
Explore a Public API: Choose a public API (e.g., Pokemon API, weather API, or news API). Write a Python program that makes a request and prints the data. Handle errors and display the data nicely.
Build a Simple Weather CLI: Build a command-line program that takes a city name as input and prints the current weather using a weather API. Add error handling for invalid city names or network issues.
API Scavenger Hunt: Find at least 3 public APIs (they can be from this list: weather, news, jokes, Pokemon). Write a Python script that makes a request to each API and prints the response data. Document what each API returns.
Build an API Dashboard: Build a Python program that fetches data from at least 3 different APIs (e.g., weather, news, and currency exchange). Display the data in a clear, formatted way. Add a refresh option to get new data.
Fill-in-the-Blank Answers:
True or False Answers: 1-T, 2-F, 3-F, 4-T, 5-F, 6-T, 7-F, 8-F, 9-T, 10-T
Multiple Choice Answers: 1-A, 2-B, 3-B, 4-B, 5-C, 6-A, 7-A, 8-B, 9-B, 10-B, 11-B, 12-A, 13-C, 14-B, 15-C
requests library makes HTTP easy.In Module 4, we will explore Network Automation โ Using Python to Manage Network Devices. You will learn how to use Python to connect to routers, switches, and other network devices to automate tasks like configuration and monitoring.
To prepare, think about these questions:
You are now ready for Module 4. Keep coding and automating!
๐ Congratulations! You have completed Module 3: HTTP and Working with APIs. See you in Module 4!