Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Requests get() Method



The Python Requestsget() 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 Requestsget() method −

requests.get(url, params=None, **kwargs)

Parameters

Below are the parameters of the Python Requestsget() 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 requestsget() method −

import requestsresponse = requests.get('https://www.tutorialspoint.com')print(response.url)

Output

https://www.tutorialspoint.com/

Example 2

The 'params' parameter ofget() 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 requestsparams = {'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 theget() method. The following is the basic example of the authenticaton −

import requestsfrom requests.auth import HTTPBasicAuth# Define the URLurl = 'https://httpbin.org/basic-auth/user/pass'# Define the credentialsusername = 'user'password = 'pass'# Send the GET request with Basic Authenticationresponse = requests.get(url, auth=HTTPBasicAuth(username, password))# Print the response status codeprint(response.status_code)# Print the response contentprint(response.text)

Output

200{  "authenticated": true,  "user": "user"}
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp