-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
132 lines (95 loc) · 4.36 KB
/
main.py
File metadata and controls
132 lines (95 loc) · 4.36 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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
from fastapi import FastAPI, Path, HTTPException, Query
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from typing import Annotated, Optional
import json
app = FastAPI()
class Customer (BaseModel):
id : Annotated[int, Field(...,description='ID of the customer', examples=[1,2,3])]
name : Annotated[str,Field(...,description='Name of the customer', min_length=5)]
amount : Annotated[int,Field(...,description='Total Loan Amount',gt=0)]
status : Annotated[str,Field(...,description='Status of the loan')]
city : Annotated[str,Field(...,description='City of the customer')]
class Customer_update(BaseModel):
name : Annotated[Optional[str],Field(default=None,description='Name of the customer', min_length=5)]
amount : Annotated[Optional[int],Field(default=None,description='Total Loan Amount',gt=0)]
status : Annotated[Optional[str],Field(default=None,description='Status of the loan')]
city : Annotated[Optional[str],Field(default=None,description='City of the customer')]
def getData():
with open('test.json', 'r') as f:
return json.load(f)
def saveData(data):
with open('test.json','w') as f:
json.dump(data,f)
@app.get('/')
def hello():
return {'message' : 'This is a Loan Managment System API'}
@app.get('/about')
def aboutInfo():
return {'message' : 'This is an API to manage your customers loans'}
@app.get('/customers')
def getUsers():
data = getData()
return data
@app.get('/customers/{customer_id}')
def viewCustomer(customer_id : int = Path(description='To access specific customer via an ID')):
data = getData()
target_idx = None
for idx, customer in enumerate(data):
if customer['id'] == customer_id :
target_idx = idx
break
if target_idx != None :
return data[target_idx]
raise HTTPException(status_code= 404, detail='error : customer not found')
@app.get('/sort')
def sort_customers(sort_by: str = Query(...,description='Sort on amount or id'), order_by : str = Query('asc',description='asc or desc')) :
if sort_by not in ['amount','id']:
raise HTTPException(status_code= 400, detail='Invalid sort by field, select ONLY from amount or id')
if order_by not in ['asc','desc']:
raise HTTPException(status_code= 400, detail='Invalid order by field,select ONLY from asc or desc')
data = getData()
order = True if order_by=='desc' else False
sorted_data = sorted(data, key= lambda x: x.get(sort_by,0), reverse= order)
return sorted_data
@app.post('/create')
def create_customer(customer : Customer):
data = getData()
if any(item['id'] == customer.id for item in data ):
raise HTTPException(400,detail='Customer already exists')
data.append(customer.model_dump())
saveData(data)
return JSONResponse(status_code=201,content={'message':'Customer created Successfully'})
@app.put('/edit/{customer_id}')
def update_customer(customer_id : int, customer_update : Customer_update):
data = getData()
if not any (item['id'] == customer_id for item in data):
raise HTTPException(status_code=404, detail='customer does not exist')
target_idx = None
for idx, customer in enumerate(data):
if customer['id'] == customer_id :
target_idx = idx
break
existing_customer_info = data[target_idx]
updated_customer_info = customer_update.model_dump(exclude_unset=True)
for key, value in updated_customer_info.items():
existing_customer_info[key] = value
existing_customer_info['id'] = customer_id
customer_pydantic_obj = Customer(**existing_customer_info)
existing_customer_info = customer_pydantic_obj.model_dump()
data[target_idx] = existing_customer_info
saveData(data)
return JSONResponse(status_code=200,content={'message' : 'customer updated'})
@app.delete('/delete/{customer_id}')
def delete_customer(customer_id : int):
data = getData()
if not any(item['id'] == customer_id for item in data):
raise HTTPException(status_code=404, detail='Customer does not exist')
target_idx = None
for idx,customer in enumerate(data):
if customer['id'] == customer_id:
target_idx = idx
break
del data[target_idx]
saveData(data)
return JSONResponse(status_code=200, content={'message' : 'Customer deleted successfully'})