Python Requests options() Method
The Python Requests options() method is used to send an OPTIONS request to a specified URL. The OPTIONS requests are used to describe the communication options for the target resource which typically use retrieve the allowed HTTP methods such as GET, POST, PUT, DELETE, etc. which can be used on a resource.
This method is often utilized in CORS i.e. Cross-Origin Resource Sharing, preflight requests to check what methods and headers are permitted when accessing resources across different domains. This method returns a response object containing status codes and headers but no body content.
Syntax
Following is the syntax and parameters of Python Requests options() method −
requests.options()
Parameter
This parameter does not take any parameters.
Return value
This method returns a Response object.
Example 1
Following is the basic example of OPTIONS request with the help of python requests options() method −
import requests
# Define the URL
url = 'https://www.google.com'
# Send the OPTIONS request
response = requests.options(url)
# Print the response status code
print('Status Code:', response.status_code)
# Print the response headers
print('Response Headers:', response.headers)
Output
Status Code: 405
Response Headers: {'Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1592', 'Date': 'Mon, 24 Jun 2024 11:06:13 GMT', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000'}
Example 2
The python requests options() method typically doesn't include request parameters in the body like POST or PUT requests. Instead the parameters can be usually passed through the URL as query parameters.
Here's how we can send an OPTIONS request with parameters using the requests module in Python −
import requests
params = {'key': 'value'}
response = requests.options('https://www.google.com/options-endpoint', params=params)
print(response.url)
print(response.headers)
Output
https://www.google.com/options-endpoint?key=value
{'Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1577', 'Date': 'Mon, 24 Jun 2024 11:13:48 GMT', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000'}
Example 3
We can send cookies with an OPTIONS request using the cookies parameter of the requests.options() method. Here is the example of it −
import requests
# Define the URL
url = 'https://www.google.com'
# Send the OPTIONS request
response = requests.options(url)
# Print the response status code
print('Status Code:', response.status_code)
# Print the response headers
print('Response Headers:', response.headers)
Output
Status Code: 405
Response Headers: {'Content-Type': 'text/html; charset=UTF-8', 'Referrer-Policy': 'no-referrer', 'Content-Length': '1592', 'Date': 'Mon, 24 Jun 2024 11:06:13 GMT', 'Alt-Svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000'}
python_modules.htm