python requests response

Python Requests Response

When working with web APIs or web scraping, you may need to send HTTP requests and receive responses from servers. Python's requests library is a popular tool for making HTTP requests and handling responses.

Sending a GET Request

To send a GET request using requests, first import the library:


import requests

Then, use the get() method to send a GET request to a URL:


response = requests.get('https://example.com')

The response object contains the server's response to the request. You can check the response status code and content:


print(response.status_code)
print(response.content)

Sending POST, PUT, and DELETE Requests

You can also send POST, PUT, and DELETE requests using the post(), put(), and delete() methods, respectively. You can specify data to be sent with the request using the data parameter:


data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://example.com', data=data)

Sending Headers

You can send headers with your requests using the headers parameter:


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

Handling Response Content

The response object contains the server's response content as bytes. You can decode the content to a string using the decode() method:


content = response.content.decode('utf-8')
print(content)

You can also load the content into a JSON object using the json() method:


json_data = response.json()
print(json_data)

Error Handling

If the server returns an error response (e.g. 404 Not Found), the response object's ok attribute will be set to False. You can raise an exception if the response is not OK:


response = requests.get('https://example.com/notfound')
if not response.ok:
    raise Exception('Error: {}'.format(response.status_code))

Conclusion

The requests library is a powerful tool for making HTTP requests and handling responses in Python. With this library, you can easily send GET, POST, PUT, and DELETE requests, and handle response content and errors.