Q1. What is the requests library used for?
Requests is a simple HTTP library for Python, used to send HTTP requests (GET, POST, etc.) and handle responses. It abstracts complexities of urllib and provides a cleaner API. It's essential for interacting with web APIs.
Q2. How do you make a GET request?
Use requests.get(url). Example:
import requests
response = requests.get(''https://api.example.com/data'')
print(response.status_code)
print(response.json()) # if JSON responseQ3. How do you send POST data?
Use requests.post() with data or json parameter. Example:
payload = {''key'': ''value''}
response = requests.post(''https://httpbin.org/post'', json=payload) For form data, use data=.Q4. How do you handle authentication with requests?
Use auth parameter for basic auth, or pass headers. Example:
response = requests.get(''https://api.example.com'', auth=(''user'', ''pass''))
headers = {''Authorization'': ''Bearer token''}
response = requests.get(''https://api.example.com'', headers=headers)Q5. How do you handle exceptions in requests?
"Use try-except for exceptions like ConnectionError, Timeout, HTTPError. Example:
try:
response = requests.get(url, timeout=5)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(fError: {e}")