I have a Django app and a workflow like this in my views.py
:
my front end makes a call to my back end which uses the params received from front end to make an API call to an external API. I map the response from the external API to my serializer and check if the serializer is valid before saving the response to database. What I need help with is how to properly check for the responses from the external API and catch any errors getting from there? Can I just use try/except? At the moment I don't know about their exact responses but that is something I can clarify later.
This is my class from views.py
:
class Example(generics.ListCreateAPIView):
permission_classes = (AllowAny,)
serializer_class = ExampleSerializer
def post(self, request, format=None):
pin = request.data['pin']
id = str(uuid.uuid4())
post_obj = {'pin': pin, 'id': id}
data = requests.post(url, data=json.dumps(post_obj))
json_result = data.json()
serializer = ExampleSerializer(data=json_result['data'])
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
with request you can use the built-in provided raise_for_status
:
from requests.exceptions import HTTPError
with requests.Session() as api:
response = api.post(url, data=json.dumps(post_obj))
try:
api.raise_for_status()
except HTTPError as e:
return Response(
{"api": "Cannot load API response"},
status=status.HTTP_400_BAD_REQUEST
)
json_result = response.json()
This will raise an HTTPError
if the result is not valid, you just add you'r response and it will works