What is requests.get() in Python?
requests.get() is a method in Python's requests library that sends an HTTP request to a specified URL and retrieves the response. It is commonly used to retrieve data from web APIs or to access web pages.
Example usage:
import requests
response = requests.get('https://www.example.com')
print(response.content)
In the above example, the requests library is imported and requests.get() is used to send a GET request to the URL 'https://www.example.com'. The response is then stored in the variable 'response', and the content of the response is printed.
Response Object
The response object returned by requests.get() contains several attributes and methods that can be used to analyze and manipulate the response data.
response.status_code
- the status code of the response (e.g. 200 for success)response.headers
- a dictionary containing the response headersresponse.content
- the raw response content in bytesresponse.text
- the response content as a string (decoded using the encoding specified in the response headers)response.json()
- parses the response content as JSON and returns a dictionary
Handling Errors
When making requests with requests.get(), it's important to handle any errors that may occur. The following example demonstrates how to handle a request that returns a non-200 status code:
import requests
response = requests.get('https://www.example.com/404')
if response.status_code == 200:
print(response.text)
else:
print(f'Request failed with status code {response.status_code}')
In the above example, a request is made to a URL that returns a 404 status code. The if statement checks if the status code is 200, and if it's not, an error message is printed.
Conclusion
requests.get() is a powerful and easy-to-use method in Python's requests library for sending HTTP requests and retrieving responses. By understanding how to use this method and handle errors, you can effectively access data from web APIs and web pages.