python requests module put example

Python Requests Module Put Example

As a developer, I have had several instances where I needed to update data on a server. One way to do this is by using HTTP PUT method. In Python, we can use the requests module to make HTTP requests, including PUT requests.

Example:


      import requests

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

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

      print(response.status_code) # Should print 200 if successful

    

In the code above, we first import the requests module. Then, we define the URL to which we want to send the PUT request. We also define the data that we want to update, in this case, a name and an age.

We then use the requests.put() method to send the request. We pass in the URL and the data as parameters. In this example, we are sending the data as JSON, but we can also send it as form data or plain text.

Finally, we print the status code of the response to confirm whether the request was successful.

Multiple Ways to Send Data

Aside from sending data as JSON, we can also send it as form data or plain text. Here are examples of how to do that:

  • Sending Data as Form Data

      import requests

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

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

      print(response.status_code) # Should print 200 if successful

    

In the code above, we pass the data as a dictionary to the data parameter instead of the json parameter.

  • Sending Data as Plain Text

      import requests

      url = 'https://example.com/api/data/1'
      data = 'John,30'

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

      print(response.status_code) # Should print 200 if successful

    

In the code above, we pass the data as a string to the data parameter. Note that we do not specify a content type, so the server will assume that the data is plain text.

That's it! Hopefully, this example helps you understand how to use the requests module to send HTTP PUT requests in Python.