python requests body

Python Requests Body

Python Requests is a popular and powerful library used to send HTTP requests from Python. It allows us to send HTTP/1.1 requests using Python, which means we can access web pages, APIs, and other resources over the internet programmatically.

What is the Body of a Request?

The body of a request contains data that needs to be sent to the server. When we make a POST, PUT, or PATCH request, we need to include data in the body of the request. This data can be in various formats like JSON, XML, or plain text.

Sending Data in the Request Body using Python Requests

To send data in the request body using Python Requests, we need to pass the data as a parameter to the requests.post(), requests.put(), or requests.patch() method.


import requests

url = 'https://example.com/api'
data = {'name': 'John', 'age': 25}

response = requests.post(url, data=data)

print(response.text)

In the above example, we are sending a POST request to https://example.com/api with the data {'name': 'John', 'age': 25}. The data parameter is used to pass the data in the request body.

Sending JSON Data in the Request Body using Python Requests

If we want to send JSON data in the request body, we need to use the json parameter instead of the data parameter. The json parameter automatically serializes the data as JSON.


import requests

url = 'https://example.com/api'
data = {'name': 'John', 'age': 25}

response = requests.post(url, json=data)

print(response.text)

In the above example, we are sending a POST request to https://example.com/api with the JSON data {'name': 'John', 'age': 25}.

Sending Files in the Request Body using Python Requests

If we want to send files in the request body, we need to use the files parameter. The files parameter allows us to upload files as part of the request.


import requests

url = 'https://example.com/upload'
files = {'file': open('file.txt', 'rb')}

response = requests.post(url, files=files)

print(response.text)

In the above example, we are sending a POST request to https://example.com/upload with the file file.txt as part of the request.

Conclusion

In this article, we learned how to send data in the request body using Python Requests. We saw how to send data in various formats like plain text, JSON, and files. Python Requests makes it easy to send HTTP requests and work with APIs and other web resources.