Python Requests GET method :

The GET is an HTTP method of requests module in python. HTTP method either sends the data or receive the data from the server. So, it acts as a bridge between a client and a server.

The get() method of requests module sends a GET request to a server. That means we are sending requests to get data from a resource on the web. Moreover, the data transmitted by the GET method is visible in the URL, so it is not suitable to pass sensitive information. The length of the URL is limited by the GET method, as it assigns data to a server environment variable. This means the total amount of data sent is also limited.

Method Signature

The signature for the get method is as shown below.

requests.get(url, params={key:value}, args)

Method parameters and return type

  • Here, the get method takes three parameters as listed below.
    • url – Mandatory parameter. It specifies the URL
    • params – It sends a dictionary, list of tuples, bytes to send as a query string. This is an optional parameter.
    • args – It can pass several arguments like cookies, headers, proxies, timeout, stream, auth and cert. These arguments are optional.
  • However, it returns a response object.

Requests GET method Examples:

Example 1: In this case, we will send requests to a URL and print the status code of its response. However, it will return code 200 on success.

#Importing requests module
import requests

# variable storing url 
url="https://onlinetutorialspoint.com/python"

# Making a GET request
r = requests.get(url)
  
# Checking status code of response 
# success code - 200
# Error code - 404
print("Status code - ",r.status_code)

Output

Status code - 200

Example 2: In this case, we will use the header parameter to set the HTTP headers on the given URL. However, it will return code 200 on success.

#Importing requests module
import requests

# variable storing url 
url = "https://onlinetutorialspoint.com/python"

#Using the headers parameter to set the HTTP headers:
x = requests.get(url, headers = {"HTTP_HOST": "TUTORIAL"})

print("Status code - ",x.status_code)

Output

Status code - 200

Example 3: In this case, it will return the status code if the response is received before the timeout. However, it will raise ReadTimeout Exception, if the response is not received before timeout. However, it will return code 200 on success.

#Importing requests module
import requests

# variable storing url 
url = "https://onlinetutorialspoint.com/python"

#Using the timeout parameter 
x = requests.get(url, timeout=10)

print("Status code - ",x.status_code)

Output

Status code - 200

Conclusion

Hence, the get() method retrieves the data from the requested resource on the web specified by URL.

References

Happy Learning 🙂

Leave A Comment