Name : Pruthvi M Subject code: 21EC643
USN: 1EP21EC071 HTTP IN PYTHON Class: 6th (B sec)
Using HTTP in Python
Introduction
HTTP (HyperText Transfer Protocol) is the foundation of data communication on the web.
Python provides several libraries for making HTTP requests, with requests being the most
popular due to its simplicity and ease of use. This report will cover the basics of using the
requests library to perform common HTTP operations, including GET and POST requests,
handling responses, and dealing with errors.
Getting Started with requests
First, ensure the requests library is installed. You can install it using pip:
>>>pip install requests
Making a GET Request
A GET request is used to retrieve data from a server. Here's a simple example:
Example:
import requests
response = [Link]('[Link]
if response.status_code == 200:
print('Success:', [Link]())
else:
print('Failed to retrieve data:', response.status_code)
In this example, the [Link] method sends a GET request to the specified URL. The
response object contains several useful properties, such as status_code (HTTP status code) and
json() (parsed JSON content).
Example:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = [Link]('[Link] data=payload)
if response.status_code == 200:
print('Success:', [Link]())
else:
print('Failed to submit data:', response.status_code)
In this example, [Link] sends a POST request with a payload. The server processes this
data, and the response is handled similarly to the GET request.
Handling Errors
It's crucial to handle potential errors when making HTTP requests. The requests library
provides several exception classes:
import requests
try:
response = [Link]('[Link]
response.raise_for_status() # Raise HTTPError for bad responses
print('Success:', [Link]())
except [Link] as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
Using response.raise_for_status(), you can raise an HTTPError for bad responses, making error
handling more straightforward.
Conclusion
The requests library is a powerful and user-friendly tool for making HTTP requests in
Python. It simplifies the process of interacting with web services, handling responses, and
managing errors. With the basics covered in this report, you can start integrating HTTP
requests into your Python applications efficiently.