-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path45_Requests.py
More file actions
69 lines (50 loc) · 1.75 KB
/
45_Requests.py
File metadata and controls
69 lines (50 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# Installation
# To install requests library via pip, use the following command:
# pip install requests
# Syntax
# requests.get(url, params={key: value}, **kwargs)
# Making a Simple GET Request
import requests
response = requests.get("https://www.geeksforgeeks.org/")
print(response.status_code)
# Sending GET Requests with Parameters
import requests
response = requests.get("https://api.github.com/users/naveenkrnl")
print(response.status_code)
print(response.content)
# Response object
import requests
response = requests.get('https://api.github.com/')
print(response.url)
print(response.status_code)
# POST Request Example
import requests
payload = {'username': 'test', 'password': 'test123'}
response = requests.post("https://httpbin.org/post", data=payload)
print(response.text)
# Authentication using Python Requests
import requests
from requests.auth import HTTPBasicAuth
response = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
print(response.status_code)
# SSL Certificate Verification
import requests
response = requests.get('https://expired.badssl.com/', verify=False)
print(response.status_code)
# Providing a custom certificate:
import requests
response = requests.get('https://github.com/', verify='/path/to/certfile')
print(response.status_code)
# Error Handling with Requests
import requests
try:
response = requests.get("https://www.example.com/", timeout=5)
response.raise_for_status()
except requests.exceptions.HTTPError as errh:
print("HTTP Error:", errh)
except requests.exceptions.ConnectionError as errc:
print("Connection Error:", errc)
except requests.exceptions.Timeout as errt:
print("Timeout Error:", errt)
except requests.exceptions.RequestException as err:
print("Something Else:", err)