GET and POST requests using Python

Here is a quick guide to perform GET and POST requests using Python.

We are going to use requests module. Install it using pip.

pip install requests

Here is the code to perform the GET request.

import requests
url = 'https://codeforgeek.com'

x = requests.get(url)
print(x)

If you want to send parameters, pass it along with the URL.

import requests
url = 'https://codeforgeek.com'
data = {'id': 123}
x = requests.get(url,params = data)
print(x)

Here is how to send the POST request.

import requests

url = 'https://codeforgeek.com'
data = {'key': 'value'}

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

print(r.text) // or r.json

Here is the code send the file in POST request in the multipart form.

import requests

url = 'https://codeforgeek.com'
data = {'key': 'value'}
file = ('file': open('filepath','rb')) //example /home/pi/Desktop/user.pdf

r = requests.post(url, files = file, data = data)

print(r.text) // or r.json
Pankaj Kumar
Pankaj Kumar
Articles: 209