Python Requests Library – Notes
The requests library in Python is a simple and powerful HTTP client used to send HTTP/HTTPS
requests. It is widely used for interacting with web APIs, downloading data, sending form data,
authentication, and automation of web tasks.
1. Installation
Concept:
Requests is not part of Python's standard library, so it must be installed separately.
Syntax:
pip install requests
Example Program:
import requests
print("Requests library installed successfully!")
2. Importing Requests
Concept:
Before using the library, it must be imported into your Python program.
Syntax:
import requests
import requests
response = [Link]("[Link]
print(response.status_code)
3. Sending GET Request
Concept:
A GET request retrieves data from a server.
Syntax:
[Link](url)
import requests
url = "[Link]
response = [Link](url)
print(response.status_code)
print([Link])
4. Sending POST Request
Concept:
POST requests send data to a server (commonly used in forms or APIs).
Syntax:
[Link](url, data=data_dictionary)
import requests
url = "[Link]
data = {"username": "admin", "password": "1234"}
response = [Link](url, data=data)
print([Link]())
5. Sending PUT Request
Concept:
PUT updates an existing resource on the server.
Syntax:
[Link](url, data=data_dictionary)
import requests
url = "[Link]
data = {"name": "Bhuvan"}
response = [Link](url, data=data)
print([Link])
6. Sending DELETE Request
Concept:
DELETE removes a resource from the server.
Syntax:
[Link](url)
import requests
url = "[Link]
response = [Link](url)
print(response.status_code)
7. Response Object
Concept:
The response returned from a request contains useful information.
Common Attributes:
response.status_code -> HTTP status code
[Link] -> response content as text
[Link]() -> response in JSON format
[Link] -> server headers
import requests
response = [Link]("[Link]
print(response.status_code)
print([Link])
print([Link]())
8. Sending Headers
Concept:
Headers provide additional information to the server such as user-agent or authorization.
Syntax:
[Link](url, headers=headers_dictionary)
import requests
url = "[Link]
headers = {
"User-Agent": "MyPythonApp"
}
response = [Link](url, headers=headers)
print([Link])
9. Query Parameters
Concept:
Query parameters are used to pass data in the URL.
Syntax:
[Link](url, params=parameters_dictionary)
import requests
url = "[Link]
params = {
"name": "Bhuvan",
"age": 20
}
response = [Link](url, params=params)
print([Link])
print([Link]())
10. Timeout Handling
Concept:
Timeout prevents the program from waiting forever for a server response.
Syntax:
[Link](url, timeout=seconds)
import requests
try:
response = [Link]("[Link] timeout=2)
print([Link])
except [Link]:
print("Request timed out!")
11. Exception Handling
Concept:
Requests provides several exception classes to handle errors safely.
Common Exceptions:
[Link]
[Link]
[Link]
import requests
try:
response = [Link]("[Link]
except [Link] as e:
print("Error:", e)