Python Requests get() Method
The Python Requests get() method is used to send an HTTP GET request to a specified URL. This method retrieves data from the specified server endpoint.
This method can accept optional parameters such as params for query parameters, headers for custom headers, timeout for request timeout and auth for authentication.
This method returns a Response object containing the server's response data, status code, headers and more. It is commonly used for fetching data from APIs or web pages.
Syntax
Following is the syntax and parameters of Python Requests get() method −
requests.get(url, params=None, **kwargs)
Parameters
Below are the parameters of the Python Requests get() method −
- url: This is the url of the resource we want to fetch.
- params(dict or bytes, optional): Dictionary or bytes to be sent in the query string for the request.
- kwargs(optional): Optional arguments that can be passed including headers, cookies, authentication etc.
Return value
This method returns a Response object.
Example 1
Following is the basic example which involves sending a request to a specified URL and handling the response with the help of python requests get() method −
import requests
response = requests.get('https://www.tutorialspoint.com')
print(response.url)
Output
https://www.tutorialspoint.com/
Example 2
The 'params' parameter of get() method is used to get params of the url. This parameter accepts a dictionary of key-value pairs that will be encoded as query parameters in the URL. Here is the example −
import requests
params = {'q': 'python requests', 'sort': 'relevance'}
response = requests.get('https://www.tutorialspoint.com', params=params)
print(response.url)
Output
https://www.tutorialspoint.com/?q=python+requests&sort=relevance
Example 3
The requests module supports several types of authentication by specifying the parameter 'auth' in the get() method. The following is the basic example of the authenticaton −
import requests from requests.auth import HTTPBasicAuth # Define the URL url = 'https://httpbin.org/basic-auth/user/pass' # Define the credentials username = 'user' password = 'pass' # Send the GET request with Basic Authentication response = requests.get(url, auth=HTTPBasicAuth(username, password)) # Print the response status code print(response.status_code) # Print the response content print(response.text)
Output
200
{
"authenticated": true,
"user": "user"
}
python_modules.htm