Last modified: Nov 12, 2024 By Alexander Williams

Python requests.GET(): Complete Guide for HTTP GET Requests

The requests.get() method is a powerful tool in Python for making HTTP GET requests. This guide will help you understand how to use it effectively for web scraping and API interactions.

Installation and Basic Usage

Before using requests, ensure it's installed. If you encounter installation issues, check out our guide on solving No module named requests in Python.

Here's a simple example of making a GET request:


import requests

response = requests.get('https://api.github.com')
print(response.status_code)


200

Handling Response Status

Checking the response status is crucial when making HTTP requests. Learn more about how to get requests Status Code in detail.


response = requests.get('https://api.github.com')
if response.status_code == 200:
    print("Success!")
else:
    print(f"Request failed with status code: {response.status_code}")

Working with Headers and Parameters

You can customize your requests with headers and parameters. For more details, see our guide on sending requests with headers and data.


headers = {'User-Agent': 'Mozilla/5.0'}
params = {'key': 'value'}
response = requests.get('https://api.example.com', headers=headers, params=params)

Fetching Website Content

The requests.get() method is perfect for getting website source code and working with various content types.


response = requests.get('https://example.com')
print(response.text[:100])  # Print first 100 characters

Using Proxies

For scenarios requiring proxy usage, check our guide on using Python requests with proxy.


proxies = {
    'http': 'http://proxy.example.com:8080',
    'https': 'https://proxy.example.com:8080'
}
response = requests.get('https://api.example.com', proxies=proxies)

Handling Images and Media

When working with images, you might need to get image size from URL using requests.


response = requests.get('https://example.com/image.jpg')
with open('image.jpg', 'wb') as f:
    f.write(response.content)

Error Handling

Always implement proper error handling in your requests:


try:
    response = requests.get('https://api.example.com', timeout=5)
    response.raise_for_status()
except requests.exceptions.RequestException as e:
    print(f"An error occurred: {e}")

Conclusion

The requests.get() method is an essential tool for HTTP requests in Python. Remember to handle errors, set appropriate timeouts, and follow best practices for reliable web interactions.