Home > Blockchain >  Making ajax request with Python not returning an intended response
Making ajax request with Python not returning an intended response

Time:03-20

Trying to make a same request implemented in Code (1) using python, which is a part of a backend data fetching process on an online card game card lookup website (enter image description here

(3) Python code

import requests
res = requests.get(
    url='https://splintx.com/db.php',
    params={
        'card':
            {
                'id': 141,
                'foil': 0,
                'edition': 4,
            }

    },
)

(4) Unintended response - response[1] is supposed to have price history data but is empty

[["2020-08-24 12:00:01am","2020-08-25 12:00:01am","2020-08-26 12:00:01am", ...], []]

CodePudding user response:

Since you are JSON-encoding your Javascript, you need to JSON-encode your Python as well:

import requests
res = requests.get(
    url='https://splintx.com/db.php',
    params={
        'card': json.dumps(
            {
                'id': 141,
                'foil': 0,
                'edition': 4,
            }
        )
    },
)

CodePudding user response:

After a further debugging, I found that the data: {card: priceData} is actually sent as Form Data, not as query string. (Differences between Form Data and query string)
Form Data is sent inside the HTTP body of a POST request, and with the help of this, I have realised the below working code.

Not quite sure why Session should be created upfront when dealing with Form Data yet.

import requests

pricedata = '[{"id":141,"foil":0,"edition":4}]'
data = {'card': pricedata}

session = requests.Session()
req = session.post('https://splintx.com/db.php', data=data)

print(req.content)
  • Related