I am trying t write a web controller for an API with GET, POST, PUT functionalities. 1. In the method that handles the requests , especially POST and PUT, I want to validate if the required keys/fields are present in the request body. 2. I also want to check the authorization key present in the request header and throw unauthorized error etc. as response.
Is there an elegant way of doing this in python, write multiple if...else
doesn't look elegant.
I have the following code which handles the request body:
from werkzeug.wrappers import BaseResponse as Response
.
.
.
root = ET.fromstring(data)
for child in root:
order_completed_date = child.find('Order_Completed_Date')
if order_completed_date is None:
#return json.loads({"status":"400", "message":"Order_Completed_Date is missing"})
return Response('Bad Request, Order_Complete_At missing', status=400)
else:
order_completed_date = order_completed_date.text
order_id = child.find('Order_Number')
if order_id is None:
return Response('Bad Request, Order_Number missing', status=400)
else:
order_id = order_id.text
product_id =child.find('SKU')
if product_id is None:
return Response("Bad request, SKU is missing", status=400)
else:
product_id = product_id.text
.
.
.
So on, I'm writing if else for each field