Python POST Request with Headers and Body

In this lesson we want to learn about Python POST Request with Headers and Body.

 

What is POST Request ?

POST request is an HTTP request method used to submit data to server for processing. it is often used to send data to server side script or API endpoint for further processing. Unlike  GET request which retrieves data from server, POST request sends data to the server.

data sent with POST request is usually in the body of the request, rather than in the URL. this allows for the submission of more complex data such as forms with multiple fields or binary data. the format of the data in the body of POST request is specified by the Content-Type header, which can be set to application/x-www-form-urlencoded for traditional form data, or application/json for JSON data.

In general we can say that POST requests should be used for actions that modify data on the server such as creating new resource or updating an existing resource. GET requests should be used for actions that retrieve data from the server without modifying it such as retrieving list of resources or single resource.

 

 

Python POST Request with Headers and Body

In Python you can make POST request with headers and body using requests library. requests library is  popular third party library that simplifies making HTTP requests in Python. this is an example of making POST request with headers and body:

In this example,  requests.post function is used to make POST request to specific url. headers argument is used to pass headers for the request, in this case Content-Type header with value of ‘application/json’. json argument is used to pass the body of the request in this case  dictionary containing the keys name and age.

 

response from the server is stored in the response variable. you can use response.status_code attribute to get the HTTP status code of the response, and the response.text attribute to get the body of the response as a string.

Note this example assumes that the server accepts and returns JSON data. if the server accepts and returns a different format you will need to adjust the Content-Type header and the format of the body accordingly.

 

Learn More on Python

Leave a Comment