Http methods in Python : Technology


Python HTTP Methods.

In Python, you can make HTTP requests using the built-in urllib or requests library. To make requests using different HTTP methods, you can use the following methods:

GET method:
To make a GET request, you can use the requests.get() method or urllib.request.urlopen() method.

Example using requests library:
import requests

response = requests.get(\’https://www.example.com\’)
print(response.status_code)
print(response.text)


Example using urllib library:
from urllib.request import urlopen

response = urlopen(\’https://www.example.com\’)
print(response.status)
print(response.read().decode(\’utf-8\’))


POST method:
To make a POST request, you can use the requests.post() method or urllib.request.urlopen() method with the data parameter.

Example using requests library:
import requests

payload = {\’key1\’: \’value1\’, \’key2\’: \’value2\’}
response = requests.post(\’https://www.example.com\’, data=payload)
print(response.status_code)
print(response.text)


Example using urllib library:
from urllib.request import urlopen, Request
from urllib.parse import urlencode

data = urlencode({\’key1\’: \’value1\’, \’key2\’: \’value2\’}).encode(\’utf-8\’)
req = Request(\’https://www.example.com\’, data=data)
response = urlopen(req)
print(response.status)
print(response.read().decode(\’utf-8\’))


PUT method:
To make a PUT request, you can use the requests.put() method or urllib.request.urlopen() method with the data parameter.

Example using requests library:
import requests

payload = {\’key1\’: \’value1\’, \’key2\’: \’value2\’}
response = requests.put(\’https://www.example.com\’, data=payload)
print(response.status_code)
print(response.text)


Example using urllib library:

from urllib.request import Request, urlopen
from urllib.parse import urlencode

data = urlencode({\’key1\’: \’value1\’, \’key2\’: \’value2\’}).encode(\’utf-8\’)
req = Request(\’https://www.example.com\’, data=data, method=\’PUT\’)
response = urlopen(req)
print(response.status)
print(response.read().decode(\’utf-8\’))


DELETE method:
To make a DELETE request, you can use the requests.delete() method or urllib.request.urlopen() method with the method parameter set to \’DELETE\’.

Example using requests library:
import requests

response = requests.delete(\’https://www.example.com\’)
print(response.status_code)
print(response.text)


Example using urllib library:
from urllib.request import Request, urlopen

req = Request(\’https://www.example.com\’, method=\’DELETE\’)
response = urlopen(req)
print(response.status)
print(response.read().decode(\’utf-8\’))

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *