hljs.initHighlightingOnLoad();
Python Requests Quickstart
If you are looking to make HTTP requests in Python, the requests library is a popular choice. It is a simple and elegant way to make HTTP requests with Python.
Installation
You can install the requests library using pip:
pip install requestsBasic Usage
Here is an example of how to make a GET request using requests:
import requests
response = requests.get('https://www.example.com')
print(response.status_code)
print(response.text)- The
getfunction sends a GET request to the specified URL. - The
status_codeattribute returns the HTTP status code of the response. - The
textattribute returns the content of the response as a string.
If you need to send data with your request, you can use the data parameter:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.get('https://www.example.com', params=payload)
print(response.url)- The
paramsparameter is used to pass data with the request. - The
urlattribute returns the URL of the response.
If you need to send JSON data with your request, you can use the json parameter:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com', json=payload)
print(response.status_code)- The
postfunction sends a POST request to the specified URL. - The
jsonparameter is used to send JSON data with the request.
Error Handling
If there is an error with your request, requests will raise an exception. Here is an example of how to handle errors:
import requests
try:
response = requests.get('https://www.example.com')
response.raise_for_status()
except requests.exceptions.HTTPError as err:
print(err)- The
raise_for_statusfunction will raise an exception if the HTTP status code is not successful.