Python Requests Module Get Example
If you are looking for a way to send HTTP requests in Python, the requests
module is the way to go. One of the most common HTTP methods is GET, which is used to retrieve data from a server. In this article, we will explore how to use the requests.get()
method to send GET requests in Python.
Using the requests.get() method
The requests.get() method is used to send a GET request to a specified URL. It takes one mandatory argument, which is the URL of the resource you want to retrieve. Here's an example:
import requests
url = 'https://www.example.com'
response = requests.get(url)
print(response.text)
In this example, we import the requests
module and specify the URL of the resource we want to retrieve. We then pass this URL as an argument to the requests.get()
method, which sends a GET request to the specified URL.
The response object returned by the requests.get()
method contains various properties and methods that allow you to access the data returned by the server. In this example, we simply print the response text using the response.text
property.
Passing parameters in a GET request
Sometimes, you may need to pass parameters along with a GET request. For example, you may need to specify query parameters for a search API. You can pass parameters using the params
keyword argument in the requests.get()
method. Here's an example:
import requests
url = 'https://www.example.com/search'
params = {'q': 'python', 'page': 2}
response = requests.get(url, params=params)
print(response.url)
In this example, we specify the URL of the search API and the query parameters we want to pass using a dictionary. We then pass this dictionary as the params
keyword argument in the requests.get()
method. The resulting URL of the GET request is printed using the response.url
property.
Handling errors in a GET request
When sending a GET request, there may be times when the server returns an error response. The requests
module provides various methods to handle such errors. Here's an example:
import requests
url = 'https://www.example.com/404'
response = requests.get(url)
try:
response.raise_for_status()
except requests.exceptions.HTTPError as e:
print(e.response.text)
In this example, we specify a URL that returns a 404 error response. We then send a GET request using the requests.get()
method. We use a try-except block to catch any HTTP error responses returned by the server. If an error response is returned, we print the response text using the e.response.text
property.
Conclusion
The requests module provides a simple and powerful way to send HTTP requests in Python. In this article, we explored how to use the requests.get() method to send GET requests, pass parameters, and handle errors. With this knowledge, you can now retrieve data from various APIs and web services using Python.