11.4 Requests: HTTP Requests

11.4 Requests: HTTP Requests

An introduction to the Requests library for making HTTP requests and interacting with websites and APIs.

The Requests library is one of the most popular and user-friendly libraries for making HTTP requests in Python. It dramatically simplifies the process of communicating with web servers, allowing you to interact with websites and APIs, download data, submit forms, and much more, in a clean and "human" way.
An HTTP request is simply a message that a client (e.g., your browser or Python program) sends to a server to request a resource (e.g., a webpage, an image, JSON data). Requests handles all the complexities of this communication for you.
# import requests

# # Example 1: GET request to a website
# try:
#     response = requests.get("https://www.google.com")
#     print(f"Status code for Google: {response.status_code}")
#     if response.status_code == 200:
#         print("Successfully connected to Google.")
#         # print(response.text[:200]) # Prints the first 200 characters of the HTML
#     else:
#         print("Connection failed.")
# except requests.exceptions.RequestException as e:
#     print(f"An error occurred during the request: {e}")

# # Example 2: GET request to a public API (JSONPlaceholder)
# try:
#     api_url = "https://jsonplaceholder.typicode.com/todos/1"
#     response_api = requests.get(api_url)
#     print(f"Status code for API: {response_api.status_code}")
#     if response_api.status_code == 200:
#         todo_item = response_api.json()
#         print(f"Data from API: {todo_item}")
#         print(f"Title: {todo_item['title']}")
#     else:
#         print("Failed to retrieve data from API.")
# except requests.exceptions.RequestException as e:
#     print(f"An error occurred during the API request: {e}")
    
print("The Requests code is commented out. To run it, install Requests locally ('pip install requests').")
print("Requests is used for making HTTP requests (e.g., fetching data from websites or APIs).")

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.