Requests Module

Hi! In this blog I will show you how to use the requests module in Python


What are HTTP Requests?

HTTP Requests are often used to communicate to an external server from the client (your browser).

For example, you want to get data from a website.

To do that in Python the easy way, you can use the requests module.

GET, POST, PUT and DELETE

GET Requests are used to fetch data from a server.

POST Requests are used to send data to the server and (sometimes, based on the server) recieve some data relevant to what you have sent.

PUT Requests are used to update some data on the server (if it allows it).

DELETE Requests are used to delete some data on the server (if it allows it as always).

Using the Requests Module


Example for a GET Request


import requests


URL = "https://exampleDATABASE.comp/"

response = requests.get(URL)

data = response.json()

print(data)
            

Here, we are getting the data from an example (fake) database.

First we import the requests module

Then we use requests.get() to make a GET request from the url URL

After that we convert the raw data to JSON.

Then we print the data.


Example for a POST Request


import requests


URL = "https://exampleDATABASE.comp/"

dataToPost = {"key1": "value1", "key2": "value2"}

response = requests.post(URL, data=dataToPost)

print(response) # Outputs: "key 1 is value1", "key 2 is value2" ### FOR EXAMPLE
            

Here we are using the same database, but using POST Request.

First we make a variable that stores some data.

Then we use that data to post it to the server by calling requests.post().

If so, the database/server will respond to that data.

NOTICE: This will not update the database. If it supports that.


Example for a PUT Request


import requests


URL = "https://exampleDATABASE.comp/"

dataToPut = {"key1": "value1", "key2": "value2"}

response = requests.put(URL, data=dataToPut)

print(response) # Outputs: 200 ### OK
            

Here we are using the same database, but using PUT Request.

First we make a variable that stores some data.

Then we use that data to put it in the server by calling requests.put().

NOTICE: The server will get updated by your data, if it supports that.


Example for a DELETE Request


import requests


URL = "https://exampleDATABASE.comp/"


requests.delete("https://exampleDATABASE.comp/16soth.html")

            

Here we are using the same database, but using DELETE Request.

Then we delete the data from 16soth.html by calling requests.delete().

NOTICE: The server will get updated by your data, if it supports that.


So, that's it.

Hope it was helpful.