python requests

Python Requests

If you want to send HTTP requests to a website or API using Python, then you can use the requests module. It is an elegant and simple HTTP library that makes it easy to send HTTP/1.1 requests using Python.

Installing Python Requests

You can install requests using pip:

pip install requests

Sending a GET Request

To send a GET request to a website, you can use the get() method:

import requests

response = requests.get('https://www.example.com')

print(response.status_code)
print(response.text)

The get() method will return a Response object. You can access the status code using the status_code attribute and the content of the response using the text attribute.

Sending a POST Request

To send a POST request to a website, you can use the post() method:

import requests

data = {'username': 'john', 'password': 'secret'}
response = requests.post('https://www.example.com/login', data=data)

print(response.status_code)
print(response.text)

The post() method accepts a second parameter, data, which is the data to be sent in the request body. In this example, we are sending a dictionary of data.

Sending Headers

You can send headers along with your requests. Headers are useful for sending authentication tokens or user agent information.

import requests

headers = {'Authorization': 'Bearer ', 'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://www.example.com', headers=headers)

print(response.status_code)
print(response.text)

The headers are passed as a dictionary to the headers parameter of the request methods.

Handling Exceptions

Requests can raise exceptions if there is a problem with the request. You can catch these exceptions and handle them appropriately:

import requests

try:
    response = requests.get('https://www.example.com/404')
    response.raise_for_status()
except requests.exceptions.HTTPError as error:
    print(error)

The raise_for_status() method will raise an exception if the status code of the response indicates an error (like 404 Not Found). You can catch this exception and handle it in your code.