python requests library functions

Python Requests Library Functions

If you are working with web scraping or API calls in Python, then you might have come across the Python Requests library. It is a popular third-party library used to send HTTP requests and handle responses. Here are some of the commonly used functions of the Requests library:

GET Method

The GET method is used to retrieve data from a server. You can use the get() function to send a GET request to a URL and receive the response.


import requests

response = requests.get('https://www.example.com')
print(response.status_code)
print(response.content)
            

POST Method

The POST method is used to submit data to a server. You can use the post() function to send a POST request to a URL and include data in the request.


import requests

data = {'username': 'example_user', 'password': 'example_pass'}
response = requests.post('https://www.example.com/login', data=data)
print(response.status_code)
print(response.content)
            

Headers

You can customize the headers of your requests by passing a dictionary of headers to the headers parameter.


import requests

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get('https://www.example.com', headers=headers)
print(response.status_code)
print(response.content)
            

Authentication

You can authenticate yourself with the server by passing your credentials to the auth parameter.


import requests

auth = ('username', 'password')
response = requests.get('https://www.example.com', auth=auth)
print(response.status_code)
print(response.content)
            

Cookies

You can send cookies with your request by passing a dictionary of cookies to the cookies parameter.


import requests

cookies = {'session_id': '12345'}
response = requests.get('https://www.example.com', cookies=cookies)
print(response.status_code)
print(response.content)