Skip to content

Commit 34fcb39

Browse files
Merge pull request #75 from TebogoYungMercykay/development
Returning a Well Structured JSON Response
2 parents 3ff6fe9 + 6d65cd6 commit 34fcb39

File tree

10 files changed

+749
-248
lines changed

10 files changed

+749
-248
lines changed

app/main.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
from . import models
55
from .database import engine
6-
from .routers import post, user, auth, vote, consultations, disease_prediction, chats
6+
from .routers import post, user, auth, consultations, disease_prediction, chats
77
from .config import settings
88

99
models.Base.metadata.create_all(bind=engine)
@@ -23,7 +23,6 @@
2323
app.include_router(post.router)
2424
app.include_router(user.router)
2525
app.include_router(auth.router)
26-
app.include_router(vote.router)
2726
app.include_router(consultations.router)
2827
app.include_router(disease_prediction.router)
2928
app.include_router(chats.router)

app/models.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,10 @@ class Doctor(Base):
8484
address = Column(String(100), nullable=False)
8585
mobile_no = Column(String(15), nullable=True)
8686
gender = Column(String(10), nullable=False)
87-
qualification = Column(String(20), nullable=False)
87+
qualification = Column(String(50), nullable=False)
8888
registration_no = Column(String(20), nullable=False)
8989
year_of_registration = Column(DateTime, nullable=False)
90-
state_medical_council = Column(String(30), nullable=False)
90+
state_medical_council = Column(String(50), nullable=False)
9191
specialization = Column(String(30), nullable=False)
9292
rating = Column(Integer, server_default='0')
9393
is_patient = Column(Boolean, server_default='FALSE')

app/routers/auth.py

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,45 +1,69 @@
11
from fastapi import APIRouter, Depends, status, HTTPException, Response
22
from fastapi.security.oauth2 import OAuth2PasswordRequestForm
33
from sqlalchemy.orm import Session
4+
from fastapi.responses import JSONResponse
45

56
from .. import database, schemas, models, utils, oauth2
67

7-
router = APIRouter(tags=['Authentication'])
8+
router = APIRouter(
9+
prefix="/auth",
10+
tags=['Authentication']
11+
)
812

13+
MESSAGE_INVALID = "Invalid user Credentials."
914

10-
@router.post('/login', response_model=schemas.Token)
15+
@router.post('/login', response_model=schemas.JSONToken)
1116
def login(user_credentials: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(database.get_db)):
1217

1318
user_query = db.query(models.User).filter(models.User.email == user_credentials.username)
1419
user = user_query.first()
1520

1621
if not user:
17-
raise HTTPException(
18-
status_code=status.HTTP_403_FORBIDDEN, detail=f"Invalid Credentials")
22+
error_response = {
23+
"status": "error",
24+
"id": -1,
25+
"data": MESSAGE_INVALID
26+
}
27+
return JSONResponse(content=error_response, status_code=403)
1928

2029
if not utils.verify(user_credentials.password, user.password):
21-
raise HTTPException(
22-
status_code=status.HTTP_403_FORBIDDEN, detail=f"Invalid Credentials")
30+
error_response = {
31+
"status": "error",
32+
"id": -1,
33+
"data": MESSAGE_INVALID
34+
}
35+
return JSONResponse(content=error_response, status_code=403)
2336

2437
access_token = oauth2.create_access_token(data={"user_id": user.id})
2538
user_query.update({ "is_active": True, "last_login": utils.get_current_time() })
2639
db.commit()
2740

28-
return { "access_token": access_token, "token_type": "bearer" }
41+
response_obj = { "access_token": access_token, "token_type": "bearer" }
42+
return schemas.JSONToken(status="success", id=user.id, data=response_obj)
2943

3044
@router.post('/logout/{id}')
3145
def logout(id: int, db: Session = Depends(database.get_db), current_user: int = Depends(oauth2.get_current_user)):
3246
if current_user.id != id:
33-
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
34-
detail="You are not authorized to perform this action.")
47+
error_response = {
48+
"status": "error",
49+
"id": -1,
50+
"data": "You are not authorized to perform this action."
51+
}
52+
return JSONResponse(content=error_response, status_code=401)
3553

3654
logout_query = db.query(models.User).filter(models.User.id == current_user.id)
3755
logout = logout_query.first()
3856
if not logout:
39-
raise HTTPException(
40-
status_code=status.HTTP_403_FORBIDDEN, detail=f"Invalid Credentials")
57+
error_response = {
58+
"status": "error",
59+
"id": -1,
60+
"data": MESSAGE_INVALID
61+
}
62+
return JSONResponse(content=error_response, status_code=403)
63+
4164
logout_query.update({ "is_active": False })
4265
db.commit()
4366

44-
return { "status":"success", "message": "User Successfully Logged Out." }
67+
response_obj = { "status":"success", "id": current_user.id, "data": "User Successfully Logged Out." }
68+
return response_obj
4569

app/routers/chats.py

Lines changed: 50 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from fastapi import FastAPI, Response, status, HTTPException, Depends, APIRouter
22
from sqlalchemy.orm import Session
33
from typing import List, Optional
4+
from fastapi.responses import JSONResponse
45

56
from sqlalchemy import func
67
from .. import models, schemas, oauth2
@@ -14,77 +15,103 @@
1415
tags=['Chats & Feedback']
1516
)
1617

17-
@router.post('/chat_messages/{id}', response_model=schemas.ChatList)
18+
@router.post('/chat_messages/{id}', response_model=schemas.JSONChatList)
1819
def chat_messages(id: int, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):
1920
chats = db.query(models.Chat).filter(models.Chat.consultation_id == id).all()
2021
if not chats:
21-
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
22-
detail=f"Chat with id {id} not found")
22+
error_response = {
23+
"status": "error",
24+
"id": -1,
25+
"data": f"Chat with id {id} not found"
26+
}
27+
return JSONResponse(content=error_response, status_code=404)
2328

24-
return schemas.ChatList(consultation_id=id, chats=chats)
29+
response_obj = schemas.ChatList(consultation_id=id, chats=chats)
30+
return schemas.JSONChatList(status="success", id=current_user.id, data=response_obj)
2531

2632

27-
@router.post('/create_chat/{id}', response_model=schemas.ChatOut)
33+
@router.post('/create_chat/{id}', response_model=schemas.JSONChatOut)
2834
def create_message(id: int, message: schemas.Chat, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):
2935
consultation = db.query(models.Consultation).filter(models.Consultation.id == id).first()
3036
if not consultation:
31-
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
32-
detail=f"Consultation with id {id} not found")
37+
error_response = {
38+
"status": "error",
39+
"id": -1,
40+
"data": f"Consultation with id {id} not found"
41+
}
42+
return JSONResponse(content=error_response, status_code=404)
3343

3444
new_message = models.Chat(sender_id=current_user.id, consultation_id=id, **message.dict())
3545
db.add(new_message)
3646
db.commit()
3747
db.refresh(new_message)
3848

39-
return new_message
49+
return schemas.JSONChatOut(status="success", id=current_user.id, data=new_message)
4050

4151

42-
@router.post('/user_feedback/{id}', response_model=schemas.FeedbackResponse)
52+
@router.post('/user_feedback/{id}', response_model=schemas.JSONFeedbackResponse)
4353
def get_feedback(id: int, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):
4454
doctor = db.query(models.Doctor).filter(models.Doctor.doctor_id == id).first()
4555
if not doctor:
46-
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
47-
detail=f"There is Currently no Feedback from Doctors for user, id: {id}")
56+
error_response = {
57+
"status": "error",
58+
"id": -1,
59+
"data": f"There is Currently no Feedback from Doctors for user, id: {id}"
60+
}
61+
return JSONResponse(content=error_response, status_code=404)
4862

4963
reviews = db.query(models.Feedback).filter(models.Feedback.receiver_id == id).all()
5064
if not reviews:
51-
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
52-
detail=f"There is Currently no Feedback with id: {id}")
65+
error_response = {
66+
"status": "error",
67+
"id": -1,
68+
"data": f"There is Currently no Feedback with id: {id}"
69+
}
70+
return JSONResponse(content=error_response, status_code=404)
5371

5472
list_feedback = []
5573
for single_feedback in reviews:
5674
feedback_sender = db.query(models.Patient).filter(models.Patient.patient_id == single_feedback.sender_id).first()
5775
if not feedback_sender:
58-
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
59-
detail=f"Feedback Sender with id {single_feedback.sender_id} not found")
76+
error_response = {
77+
"status": "error",
78+
"id": -1,
79+
"data": f"Feedback Sender with id {single_feedback.sender_id} not found"
80+
}
81+
return JSONResponse(content=error_response, status_code=404)
6082

6183
list_feedback.append(schemas.FeedbackOut(created_at=single_feedback.created_at, feedback=single_feedback.feedback, sender=feedback_sender))
62-
63-
return schemas.FeedbackResponse(doctor_id=id, FeedBacks=list_feedback)
84+
85+
response_obj = schemas.FeedbackResponse(doctor_id=id, FeedBacks=list_feedback)
86+
return schemas.JSONFeedbackResponse(status="success", id=current_user.id, data=response_obj)
6487

6588

66-
@router.post('/post_feedback/{id}', response_model=schemas.FeedbackOutput)
89+
@router.post('/post_feedback/{id}', response_model=schemas.JSONFeedbackOutput)
6790
def post_feedback(id: int, message: schemas.FeedbackCreate, db: Session = Depends(get_db), current_user: int = Depends(oauth2.get_current_user)):
6891
doctor = db.query(models.Doctor).filter(models.Doctor.doctor_id == id).first()
6992
if not doctor:
70-
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,
71-
detail=f"Doctor with id {id} not found")
93+
error_response = {
94+
"status": "error",
95+
"id": -1,
96+
"data": f"Doctor with id {id} not found"
97+
}
98+
return JSONResponse(content=error_response, status_code=404)
7299

73100
new_feedback = models.Feedback(sender_id=current_user.id, receiver_id=id, **message.dict())
74101

75102
db.add(new_feedback)
76103
db.commit()
77104
db.refresh(new_feedback)
78105

79-
return new_feedback
106+
return schemas.JSONFeedbackOutput(status="success", id=current_user.id, data=new_feedback)
80107

81108

82109
@router.post('/whatsapp')
83110
def whatsapp():
84-
return { "status":"pending", "message": MESSAGE_UNDER_CONSTRUCTION }
111+
return { "status":"pending", "id": -1, "data": MESSAGE_UNDER_CONSTRUCTION }
85112

86113

87114
@router.post('/meeting')
88115
def meeting():
89-
return { "status":"pending", "message": MESSAGE_UNDER_CONSTRUCTION }
116+
return { "status":"pending", "id": -1, "data": MESSAGE_UNDER_CONSTRUCTION }
90117

0 commit comments

Comments
 (0)