Last modified: May 10, 2025 By Alexander Williams

HTTP Requests in Python with Requests Library

The Requests library simplifies HTTP operations in Python. It allows you to send HTTP requests easily. This guide covers its key features.

Installing the Requests Library

First, install the library using pip. Run this command in your terminal:


pip install requests

If you need help with Python imports, see our importing Python libraries guide.

Making a GET Request

The requests.get() method fetches data from a server. Here's a basic example:


import requests

response = requests.get('https://api.example.com/data')
print(response.status_code)
print(response.json())


200
{'key': 'value'}

The status_code shows the request status. 200 means success.

Sending POST Requests

Use requests.post() to send data to a server. Here's how:


data = {'username': 'admin', 'password': 'secret'}
response = requests.post('https://api.example.com/login', json=data)
print(response.text)


{"token": "abc123"}

Always handle sensitive data carefully. Never expose credentials.

PUT and DELETE Requests

Update resources with requests.put():


update_data = {'title': 'New Title'}
response = requests.put('https://api.example.com/posts/1', json=update_data)

Delete resources with requests.delete():


response = requests.delete('https://api.example.com/posts/1')
print(response.status_code)


204

Handling Response Data

The response object contains useful data:

  • response.text - String content
  • response.json() - Parsed JSON
  • response.headers - Response headers

For complex Python imports, check our Python import system guide.

Error Handling

Always handle potential errors:


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

raise_for_status() throws an error for bad status codes.

Advanced Features

The Requests library supports:

  • Session objects for persistent settings
  • File uploads
  • Authentication
  • Proxies

For module management, see our reloading modules guide.

Conclusion

The Requests library makes HTTP operations simple in Python. It supports all major HTTP methods and handles responses well. Start using it in your projects today.

Remember to handle errors and secure sensitive data. Happy coding!