What is Requests in Python?
Requests is a popular Python library used for making HTTP requests. It simplifies the process of sending HTTP/1.1 requests and handling responses in Python. Requests allow you to send HTTP/1.1 requests extremely easily.
With Requests, you can send GET, POST, PUT, DELETE, and other HTTP requests. You can also add headers, form data, multipart files, and parameters with simple Python libraries.
Installation
You can install Requests using pip, the Python package manager:
pip install requests
Usage
To use Requests in a Python script, you need to import the library:
import requests
Sending a GET Request
Here is an example of sending a GET request using the Requests library:
import requests
response = requests.get('https://www.example.com')
print(response.text)
The response object contains the response from the server, including the status code, headers, and content. In this case, we're printing out the HTML content of the page.
Sending a POST Request
You can also send a POST request with Requests:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.json())
In this example, we're sending a POST request to https://httpbin.org/post with a dictionary of form data. The response is a JSON object containing the form data we sent.
Headers and Authentication
Requests allows you to set headers and authentication for your requests:
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get('https://www.example.com', headers=headers)
print(response.text)
In this example, we're setting the User-Agent header to mimic a web browser. You can also set authentication using the auth parameter.