Learning Goals
By the end of this section you will:
know how to retrieve data from an API using a GET request
know how to send data to an API using a POST request
know how to update data via an API using PUT and PATCH requests
understand how headers and parameters work
understand how to handle errors and timeouts
The requests library allows Python programs to send HTTP/HTTPS requests easily. It’s commonly used for:
Accessing APIs
Downloading web content
Submitting forms programmatically
GET Request¶
Use GET to retrieve data from a server.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1", verify=False)
print(response.status_code)
print(response.json())Explanation of GET Code
requests.get(URL): Sends a GET request to the URL.status_code: Returns the HTTP status code (e.g., 200 means OK, 404 means Not Found).json(): Converts the response from JSON string to Python dictionary.
GET Requests Activities
Activity 1: Retrieve User Information
Write a Python script that:
Sends a GET request to
https://jsonplaceholder.typicode.com/usersPrints the names and email addresses of all users
Activity 2: Filter Posts by User
Write a Python script that:
Sends a GET request to
https://jsonplaceholder.typicode.com/postswith the query parameteruserId=3Prints the titles of all posts made by user ID 3
POST Request¶
You usually use POST to send data to a server (e.g., submit a form).
data = {
"title": "foo",
"body": "bar",
"userId": 1
}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=data, verify=False)
print(response.status_code)
print(response.json())Explanation of POST Code
post(): Sends a POST request to create a new resource.json=data: Converts the Python dictionary into a JSON payload.
POST Requests Activities
Activity 1: Submit a New Post Write a Python script that:
Sends a POST request to
https://jsonplaceholder.typicode.com/postsIncludes JSON data with a title, body, and userId
Prints the response JSON to confirm creation
Activity 2: Register a New Comment
Write a script that:
Sends a POST request to
https://jsonplaceholder.typicode.com/commentsIncludes a name, email, postId, and body in the JSON payload
Prints the new comment’s ID from the response
PUT and PATCH Requests¶
Use PUT to replace the entire record.
put_data = {
"id": 1,
"title": "updated title",
"body": "updated body",
"userId": 1
}
response = requests.put("https://jsonplaceholder.typicode.com/posts/1", json=put_data, verify=False)
print(response.json())Explanation of PUT Code
put_data: This dictionary contains the complete updated data for the resource withID1.requests.put(...): This sends a PUT request to the server to replace the existing data at/posts/1.json=put_data: The data is sent in JSON format, which is what most APIs expect.response.json(): The server replies with the updated record, which we print.
PUT Requests Activities
Activity 1: Replace a Post
Write a script that:
Sends a PUT request to
https://jsonplaceholder.typicode.com/posts/1Replaces the entire post with new
title,body, anduserIdPrints the full updated record from the response
Activity 2: Reset a User Profile
Write a script that:
Sends a PUT request to
https://jsonplaceholder.typicode.com/users/5Replaces all user fields (name, username, email, etc.) with new values
Prints confirmation that the user was updated
Use PATCH to update only specific fields.
patch_data = {"title": "new title only"}
response = requests.patch("https://jsonplaceholder.typicode.com/posts/1", json=patch_data, verify=False)
print(response.json())Explanation of PATCH Code
patch_data: This only includes the field you want to update — in this case, just thetitle.requests.patch(...): Sends a PATCH request to modify part of the resource.json=patch_data: Sends only the data you want to change.response.json(): The server responds with the updated record.
PATCH Requst Activities
Activity 1: Update a Post Title
Write a script that:
Sends a PATCH request to
https://jsonplaceholder.typicode.com/posts/2Changes only the
titlefieldPrints the updated post
Activity 2: Update User Email Only
Write a script that:
Sends a PATCH request to
https://jsonplaceholder.typicode.com/users/3Changes only the
emailfieldPrints the updated user data
DELETE Request¶
Sends a DELETE request to remove a resource. Often used in admin interfaces or APIs with write access.
response = requests.delete("https://jsonplaceholder.typicode.com/posts/1", verify=False)
print(response.status_code)Explanation of DELETE Code
requests.delete(...): This sends an HTTP DELETE request to the server at the URLhttps://jsonplaceholder.typicode.com/posts/1.The
/posts/1endpoint refers to a specific resource, in this case, the post with ID 1.response.status_code: This prints the HTTP response code returned by the server.200or204usually means the delete operation was successful:200 OK: The server deleted the resource and may have returned a message.204 No Content: The resource was deleted, and there’s no content in the response.
When to Use DELETE¶
You use a DELETE request when:
You want to remove a record from a server or database via an API.
You’re building an admin panel or content management system where users can remove items like posts, users, or files.
Caution¶
DELETEis destructive: once something is deleted, it usually can’t be recovered.Some APIs require authentication (e.g., an API key or token) to allow delete requests.
Many servers will respond with a 403 Forbidden or 401 Unauthorized error if proper permissions aren’t provided.
Example with Authentication (optional)
This shows how to send a DELETE request with an API token.
headers = {
"Authorization": "Bearer YOUR_TOKEN"
}
response = requests.delete("https://api.example.com/posts/42", headers=headers, verify=False)
print(response.status_code)DELETE Requests Activities
Activity 1: Delete a Post
Write a script that:
Sends a DELETE request to
https://jsonplaceholder.typicode.com/posts/10Prints the status code to confirm deletion
Activity 2: Remove a Comment
Write a script that:
Sends a DELETE request to
https://jsonplaceholder.typicode.com/comments/7Checks the status code to ensure the request was successful
Headers and Query Parameters¶
Headers are used for things like tokens, content-type, etc. Params are sent as a query string like ?userId=1
headers = {
"Authorization": "Bearer abc123"
}
params = {
"userId": 1
}
response = requests.get("https://jsonplaceholder.typicode.com/posts", headers=headers, params=params, verify=False)
print(response.url)
print(response.json())Header and Parameters Activities
Use a Fake Authorization Header
Write a Python script that:
Sends a GET request to
https://httpbin.org/headersAdds a custom
Authorizationheader:headers = {"Authorization": "Bearer abc123"}Prints the response JSON to confirm the header was received by the server
Activity: Filter Posts by User ID
Write a Python script that:
Sends a GET request to
https://jsonplaceholder.typicode.com/postsAdds a query parameter:
params = {"userId": 5}Prints the titles of all posts made by user ID 5
Error Handling¶
try:
response = requests.get("https://httpbin.org/status/404")
response.raise_for_status() # Raises HTTPError if status is 4xx or 5xx
except requests.exceptions.HTTPError as err:
print("HTTP Error:", err)
except requests.exceptions.RequestException as err:
print("Request Error:", err)Explanation of Error Handling Code
raise_for_status()helps catch failed requests.RequestExceptioncatches all other connection issues, like timeouts.
Error Handling Activity
Handle a 404 Error Gracefully
Write a Python script that:
Sends a GET request to
https://jsonplaceholder.typicode.com/posts/9999(a post that doesn’t exist)Uses
try/exceptwithresponse.raise_for_status()to detect and print a user-friendly message like:“Error: The requested post was not found (404).”
Timeouts¶
try:
response = requests.get("https://httpbin.org/delay/3", timeout=2, verify=False)
except requests.exceptions.Timeout:
print("Request timed out.")Explanation of Timeouts Code
timeout=2: Waits 2 seconds before giving up.Helps avoid hanging programs if a server is slow or down.
Timeouts Activity
Simulate and Handle a Timeout
Write a Python script that:
Sends a GET request to
https://httpbin.org/delay/5Sets a timeout of
2seconds using thetimeoutargumentCatches the timeout exception and prints:
“Request timed out. Please try again later.”
Extension Activities
Use your knowledge from this section and the Working with JSON and XML to make an API requests, then process and print the returned JSON file.
You can find a heap of APIs at Free APIs. It is easiest to use API with No authorization