GET and POST requests using Python Programming

PythonServer Side ProgrammingProgramming

Python can be used to access webpages as well as post content to the webpages. There are various modules like httplib, urllib, httplib2 etc but the requests module is simplest and can be used to write simpler yet powerful programs involving GET and POST methods.

GET method

The GET method is part of the python requests module which is used to obtain data from a web URL. In the below example we reach out to our own website and find out various responses through the get method. We get the encoding, response time and also the header and part of the body.

Example

 Live Demo

import requests

req = requests.get('http://www.tutorialspoint.com/')

# Page encoding
e = req.encoding
print("Encoding: ",e)

# Response code
s = req.status_code
print("Response code: ",s)

# Response Time
t = req.elapsed
print("Response Time: ",t)


t = req.headers['Content-Type']
print("Header: ",t)

z = req.text
print("\nSome text from the web page:\n",z[0:200])

Output

Running the above code gives us the following result −

Encoding: UTF-8
Response code: 200
Response Time: 0:00:00.103850
Header: text/html; charset=UTF-8

Some text from the web page:

POST Method

The POST method is used to send data mostly through a form to the server for creating or updating data in the server. The requests module provides us with post method which can directly send the data by taking the URL and value of the data parameter.

In the below example we post some data to the httpbin.org website through the post method and get a response on how it is posted.

Example

 Live Demo

import requests
in_values = {'username':'Jack','password':'Hello'}
res = requests.post('https://httpbin.org/post',data = in_values)
print(res.text)

Output

Running the above code gives us the following result −

{
"args": {},
"data": "",
"files": {},
"form": {
"password": "Hello",
"username": "Jack"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "28",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.22.0",
"X-Amzn-Trace-Id": "Root=1-5ef75488-969f97a68bb72642b97b6d50"
},
"json": null,
"origin": "122.xxx.yy.zzz",
"url": "https://httpbin.org/post"
}
raja
Published on 10-Jul-2020 13:27:07
Advertisements