Python Requests Example Get
If you're looking for a way to make HTTP requests in Python, the requests library is a great choice. It's intuitive, well-documented, and makes it easy to interact with APIs or scrape websites. In this post, we'll cover an example of using requests.get() to make a GET request and receive a response from a server.
Importing the Requests Library
Before we can use the requests library, we need to import it into our Python script:
import requests
Making a GET Request
Once we've imported requests, we can use the get() method to make a GET request to a specified URL:
response = requests.get("https://example.com")
The response variable now contains the server's response to our request. We can access various properties of the response, such as the HTTP status code, headers, or content:
- response.status_code: the HTTP status code returned by the server (e.g., 200 for OK, 404 for Not Found, etc.)
- response.headers: a dictionary containing the HTTP headers returned by the server (e.g., {'Content-Type': 'text/html'})
- response.content: the raw content returned by the server, in bytes
- response.text: the content returned by the server, as a string (decoded using the HTTP headers)
We can print out the HTTP status code and the content of the response like this:
print(response.status_code)
print(response.text)
If the server returns a JSON response, we can use the response.json() method to decode it into a Python object (e.g., a dictionary or a list):
json_response = response.json()
print(json_response)
Specifying Query Parameters
Sometimes we need to include query parameters in our GET requests, for example when accessing an API that expects certain parameters. We can include these parameters in the URL by appending them after a question mark (?), separated by ampersands (&). However, manually constructing the URL can be error-prone and hard to read. Instead, we can pass the parameters as a dictionary to the params parameter of the get() method:
params = {'q': 'python', 'page': 2}
response = requests.get("https://example.com/search", params=params)
This will send a GET request to https://example.com/search?q=python&page=2, with the query parameters included in the URL.
Handling Errors
If the server returns an error status code (e.g., 404 for Not Found), the requests.get() method will raise an exception of type requests.exceptions.HTTPError. To handle this error, we can use a try-except block:
try:
response = requests.get("https://example.com/nonexistent-page")
response.raise_for_status() # raises an HTTPError if the status code is >= 400
except requests.exceptions.HTTPError as err:
print(f"Error: {err}")
This will catch any HTTP errors and print out an error message.
Conclusion
The requests library is a powerful tool for making HTTP requests in Python. In this post, we covered an example of using requests.get() to make a GET request and receive a response from a server. We also looked at how to handle query parameters and errors. Hopefully, this will help you get started with the requests library and explore its many features!