Checking API Results before saving

55 views
Skip to first unread message

lone...@gmail.com

unread,
Sep 1, 2022, 7:40:27 PM9/1/22
to Django users
Hello all,

    I am sending an GET request to an external API and I would like to validate the response before I save it to my model.  How do I do this?

Thank you.

Ammar Mohammed

unread,
Sep 2, 2022, 3:15:00 AM9/2/22
to 'Rahul Chauhan' via Django users
Hello ,

You can design a serializer for each api endpoint and use it in your view to validate your data like validating forms data :
Pseducode :
res = requests.post(url+some_endpoint, data)
endpoint_serializer.validate(res.data)
if serializer.is_valid():
    #do your stuff
else :
    #do something 

Best Regards 

Ammar Mohammed

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/0b724dc1-cb08-4168-8cc0-a5eac8a7c011n%40googlegroups.com.

lone...@gmail.com

unread,
Sep 2, 2022, 4:39:53 AM9/2/22
to Django users
Ok, I have a CreateView.  The process I have now is:
blank form is created by CreateView
After I submit the data to the form, I have a post_save that calls a function that queries the API based on the values entered in the form.

When and how do I call the serializer during this process?

lone...@gmail.com

unread,
Sep 2, 2022, 4:46:26 PM9/2/22
to Django users
I have been working on this issue.  Here is what I have so far.

My Model and pre_save information--------------------------------------------------------------------------------------------:
class walmart_query_history(models.Model):
    storeNumber = models.CharField(max_length=10)
    receiptDate = models.DateField(auto_now=False, auto_now_add=False)
    cardType = models.ForeignKey(walmart_query_history_card_type, on_delete=models.CASCADE)
    purchaseAmount = models.DecimalField(max_digits=13, decimal_places=2)
    lastFour = models.CharField(max_length=4)

    class Meta:
        unique_together = (('receiptDate', 'purchaseAmount'),)

def validate_response_ask_walmart(*args, instance, **kwargs):
    pewee = instance.receiptDate
    pewee = pewee.strftime('%m-%d-%Y')
    data = call_command('validate_response_query_walmart', instance.storeNumber, str(pewee), instance.cardType, str(instance.purchaseAmount), instance.lastFour)
    valid_ser = ValidateFormSerializer(data=data)
    if valid_ser.is_valid():
        post_data = valid_ser.validated_data
    else:
        print(valid_ser.errors)
pre_save.connect(validate_response_ask_walmart, sender=walmart_query_history)

Contents of my validate_response_ask_walmart file------------------------------------------------------------------------------------------------:
class Command(BaseCommand):
    help = 'Reads Receipts'

    def add_arguments(self, parser):
        parser.add_argument('storeId', type=str)
        parser.add_argument('purchaseDate', type=str)
        parser.add_argument('cardType', type=str)
        parser.add_argument('total', type=str)
        parser.add_argument('lastFourDigits', type=str)

    def handle(self, *args, **options):


        data = {
            "storeId": options['storeId'],
            "purchaseDate": options['purchaseDate'],
            "cardType": options['cardType'],
            "total": options['total'],
            "lastFourDigits": options['lastFourDigits']
        }
        storeId = data['storeId']

        headers = {
            'sec-ch-ua': '"Chromium";v="98", " Not A;Brand";v="99", "Google Chrome";v="98"',
            'accept': 'application/json',
            'Referer': 'https://www.walmart.com/receipt-lookup',
            'content-type': 'application/json',
            'sec-ch-ua-mobile': '?0',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
            'sec-ch-ua-platform': '"Mac OS X"'
        }
 
        response = requests.post(url, json=data, headers=headers)
        # Good documentation about requests response codes.

        #print("Status Code", response.status_code)
        #print(response.text)
        #print("JSON Response ", response.json())
        base_JSON = response.json()
        #tester = base_JSON
        #return json.dumps(base_JSON, indent=4)
        self.stdout.write(type(base_JSON))


My serializer file-----------------------------------------------------------------------------------------------------------------------------------------------
from rest_framework import serializers

class ValidateFormSerializer(serializers.Serializer):
    tcNumber = serializers.CharField(max_length=255, source='receipts[0]tcNumber')

----------------------------------------------------------------------------------------

I keep getting the error code of:
AttributeError: type object 'dict' has no attribute 'endswith'

What am I missing?

lone...@gmail.com

unread,
Sep 2, 2022, 4:48:15 PM9/2/22
to Django users
json_structure.png

Toshar Saini

unread,
Sep 8, 2022, 12:47:25 PM9/8/22
to django...@googlegroups.com
You can design a serializer for validate  api  data firstly you will  pass data in serializer and after validate serializer  you will save to model
Pseducode :
res = requests.post(url+some_endpoint, data)
serializer = demoserializer(res.data)
if serializer.is_valid():
    model.objects.create(id =  serializer.validate_data['id'])
    #do your stuff
else :
    #do something 
--
Reply all
Reply to author
Forward
0 new messages