Installation
Install the package using pip:
pip install requestsCore HTTP Methods
| Method | Description |
|---|---|
| delete(url, args) | Sends a DELETE request |
| get(url, params, args) | Sends a GET request |
| head(url, args) | Sends a HEAD request |
| patch(url, data, args) | Sends a PATCH request |
| post(url, data, , args) | Sends a POST request |
| put(url, data, args) | Sends a PUT request |
| request(method, url, args) | Sends a request with a specified method |
Executing GET Requests
When retrieving data, query parameters and headers can be passed directly. Dictionaries provided to the params argument are automatically URL-encoded.
import requests
search_criteria = {'q': 'python'}
http_headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
}
resp = requests.get("https://httpbin.org/get", params=search_criteria, headers=http_headers)
print(resp.status_code)
print(resp.encoding)
print(resp.url)
print(resp.text)Output:
200
utf-8
https://httpbin.org/get?q=python
...Executing POST Requests
To submit data to a server, use the post method. Data can be sent as form-encoded data, raw bytes, or JSON. Passing a dictionary to the parameter automatically serializes the payload and sets the Content-Type header to application/.
import requests
api_endpoint = 'https://httpbin.org/post'
request_body = {'key1': 'value1'}
result = requests.post(api_endpoint, =request_body)
print(result.())Output:
{'args': {}, 'data': '{"key1": "value1"}', 'files': {}, 'form': {}, 'headers': {'Content-Type': 'application/', ...}, '': {'key1': 'value1'}, 'origin': '...', 'url': 'https://httpbin.org/post'}Injecting Headers and Cookies
Custom headers and cookies can be supplied as dictionaries to their respective parameters.
import requests
endpoint = 'https://httpbin.org/get'
custom_headers = {'X-Custom-Header': 'app-v1'}
auth_cookies = {'session_id': 'xyz789'}
output = requests.get(endpoint, headers=custom_headers, cookies=auth_cookies)
print(output.())Managing SSL Certificate Verification
Encountering SSL verification errors is common when working with environments using self-signed certificates. Setting verify=False bypasses the certificate check, and the resulting warnings can be suppressed using urllib3.
import requests
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
secure_url = 'https://self-signed.badssl.com/'
response = requests.get(secure_url, verify=False)
print(response.status_code)