Making POST Requests with the REST API

Unlike the GET method that sends the data in the URL, the POST method allows us to send data to the server in the body of the request.

For example, suppose we have a service to register a user to whom you must pass an ID and email. This information would be passed through the data attribute through a dictionary structure.The post method requires an extra field called "data," in which we send a dictionary with all the elements that we will send to the server through the corresponding method.

In this example, we are going to simulate the sending of an HTML form through a POST request, just like browsers do when we send a form to a website. Form data is always sent in a key-value dictionary format.

The POST method is available in the http://httpbin.org/post service:

In the following code we define a data dictionary that we are using with post method for passing data in the body request:

>>> data_dictionary = {"id": "0123456789"}
>>> url = "http://httpbin.org/post"
>>> response = requests.post(url, data=data_dictionary)

There are cases where the server requires that the request contains headers indicating that we are communicating with the JSON format; for those cases, we can add our own headers or modify existing ones with the "headers" parameter:

>>> data_dictionary = {"id": "0123456789"}
>>> headers = {"Content-Type" : "application/json","Accept":"application/json"}
>>> url = "http://httpbin.org/post"
>>> response = requests.post(url, data=data_dictionary,headers=headers)

In this example, in addition to using the POST method, you must pass the data that you want to send to the server as a parameter in the data attribute. In the answer, we see how the ID is being sent in the form object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.90.182