To make an HTTP GET request in Python using the requests library, you can follow these steps:
Install the requests library if you haven't already. You can do this by running the following command in your terminal:
pip install requests
Import the requests library in your Python script:
import requests
Use the requests.get()
function to make the GET request. The function takes the URL as a parameter and returns a response object. Here's an example:
response = requests.get('https://jsonplaceholder.typicode.com/posts')
You can check the response status code to verify if the request was successful:
if response.status_code == 200:
# The request was successful
print('GET request successful')
else:
# The request was unsuccessful
print('GET request failed')
You can access the response content by calling the .text
or .json()
methods on the response object. Here's an example:
print(response.text) # Get the response as plain text
print(response.json()) # Get the response as JSON
That's it! You have successfully made an HTTP GET request in Python using the requests library. Remember to handle any exceptions that may occur, such as network errors or invalid URLs.