python requests module doc

Python Requests Module Doc

If you want to interact with a website or API in Python, the requests module is a powerful tool to help you do so. To get started with the requests module, you first need to install it by running the following command:

pip install requests

Once you have the requests module installed, you can start making HTTP requests using its simple API. Here are some common use cases:

GET Request

If you want to retrieve information from a website or API, you can use a GET request. Here's how you can send a GET request in Python:

import requests

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

In this example, we're sending a GET request to the GitHub Events API and printing the response as JSON.

POST Request

If you want to send information to a website or API, you can use a POST request. Here's how you can send a POST request in Python:

import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://httpbin.org/post', data=payload)
print(response.text)

In this example, we're sending a POST request to httpbin.org with some data in the payload variable. The response is printed as plain text.

Headers and Authentication

If you need to send headers or authenticate with a website or API, you can use the headers and auth parameters of the requests functions. Here's an example:

import requests

url = 'https://api.github.com/user'
headers = {'Authorization': 'token YOUR_TOKEN_HERE'}
response = requests.get(url, headers=headers)
print(response.json())

In this example, we're sending a GET request to the GitHub API with an authorization token in the headers. The response is printed as JSON.

Handling Errors

If something goes wrong with your request, the requests module will raise an exception. You can handle these exceptions using try/except blocks. Here's an example:

import requests

url = 'http://invalidurl'
try:
    response = requests.get(url)
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print(e.response.status_code)

In this example, we're attempting to send a GET request to an invalid URL. The requests module will raise an HTTPError exception, which we catch and print the status code of the response.

Conclusion

The requests module is a powerful tool for interacting with websites and APIs in Python. Whether you need to retrieve information, send data, or authenticate with a server, the requests module can help you do so with ease.