0

I'm trying to use ajax to query the supermarket's search API, and reply with the name, price and the unit pricing. To do this using Python requests, I would use this code:

import requests
import json

payload ={
   'Filters':'[]',
   'IsSpecial':'false',
   'Location':'/shop/search/products?searchTerm=banana',
   'PageNumber':'1',
   'PageSize':'24',
   'SearchTerm':'banana',
   'SortType':'TraderRelevance'
}

url = "https://www.woolworths.com.au/apis/ui/Search/products"

data = requests.post(url, json=payload).json()

print(data['Products'][0]['Name'])
print("$", data['Products'][0]['Products'][0]['Price'], "0", sep='')
print(data['Products'][0]['Products'][0]['CupString'])
print()

print(data['Products'][1]['Name'])
print("$", data['Products'][1]['Products'][0]['Price'], "0", sep='')
print(data['Products'][1]['Products'][0]['CupString'])
print()

print(data['Products'][2]['Name'])
print("$", data['Products'][0]['Products'][2]['Price'], "0", sep='')
print(data['Products'][0]['Products'][2]['CupString'])
print()

And so on...

What I am trying to do is replicate this python code to something that can be used in a web browser. Is that something that is possible?

CDspace
  • 2,639
  • 18
  • 30
  • 36

1 Answers1

0

Syntax in the browser is nearly identical, but of course it's JavaScript, not Python.

You could use the request-promise NPM module:

const request = require('request-promise')

let url = "https://www.woolworths.com.au/apis/ui/Search/products"
let payload = {
  'Filters': '[]',
  'IsSpecial': 'false',
  'Location': '/shop/search/products?searchTerm=banana',
  'PageNumber': '1',
  'PageSize': '24',
  'SearchTerm': 'banana',
  'SortType': 'TraderRelevance'
}

request
    .post({
      url,
      json: payload,
      headers: {'Content-Type': 'application/json'}
    })
    .then(res => console.log(res))
    .catch(err => console.log(err))

You will need to print out or otherwise parse your data inside your then method, since JavaScript executes this asynchronously, not synchronously like Python does.

The question of how to include a JavaScript module in the browser is a separate one, but you can find plenty of examples on this site and via Google.

There is also the fetch API which has good browser support at this point, and doesn't require you to bring in an outside module. The syntax is very similar, you can read more on MDN here.

Matt Morgan
  • 4,900
  • 4
  • 21
  • 30
  • I don't know how to use NPM, I have looked into it and have the modules installed on my computer, but how do I put this in the HTML? I'm getting the error: 'Uncaught ReferenceError: require is not defined' – The Fancyman Jan 10 '18 at 05:20