-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_request.py
102 lines (75 loc) · 2.51 KB
/
api_request.py
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import csv
import json
import os
from typing import List
import requests
example_licence = "KCX623S"
new_member: dict = {
"name": "Dan Kiki",
"vehicle_type": "Blue Alfie",
"vehicle_color": "Blue",
"vehicle_plate": "ZG32540",
}
"""Fetch One Record"""
def get_one_record(vehicle_id):
url = f"http://127.0.0.1:8000/members/{vehicle_id}"
try:
response = requests.get(url)
if response.status_code == 200:
member = response.json()
print(member)
except Exception as e:
print(e)
"""Update One Record"""
def update_one_record(vehicle_id: str, updated_data: dict):
url = f"http://127.0.0.1:8000/members/{vehicle_id}"
try:
# Send a PUT request with the updated data as JSON in the request body
response = requests.put(url, json=updated_data)
if response.status_code == 200:
member = response.json()
print(f"Updated member: {member}")
elif response.status_code == 404:
print("Member not found.")
except Exception as e:
print(f"{e}: HTTP request failed with status code: {response.status_code}")
"""Delete One Record"""
def delete_one_record(vehicle_id):
url = f"http://127.0.0.1:8000/members/{vehicle_id}"
try:
response = requests.delete(url)
if response.status_code == 204:
print(f"Successfully deleted member with vehicle {vehicle_id}")
except Exception as e:
print(e)
"""Fetch All Records"""
def fetch_records():
url = "http://127.0.0.1:8000/members/all/"
try:
response = requests.get(url)
if response.status_code == 200:
data = response.json()
for i in data:
print(i)
except Exception as e:
print(e)
"""Upload Many Records"""
def upload_records():
url = "http://127.0.0.1:8000/members/upload/"
count = 0
filepath = os.path.join("datasets", "member_registry.csv")
with open(filepath, "r") as f:
reader = csv.DictReader(f, delimiter=",")
rows = list(reader) # Convert to a list of dictionaries
try:
response = requests.post(url, json=rows)
print(response.text)
if response.status_code == 200:
print("Successfully uploaded data")
else:
print(f"HTTP request failed with status code: {response.status_code}")
except Exception as e:
print(e)
if __name__ == "__main__":
update_one_record(vehicle_id="KDD001Q", updated_data=new_member)
# upload_records()