urllib2.HTTPError: HTTP Error 422: Unprocessable Entity

I am trying to read API.

The following python code works:

import requests
import json
url = '.....'
headers = {
                  'accept': 'application/json',
                  'SY-API-KEY': '.....',
                  'Content-Type': 'application/json',
                  }

json_data = {
    'ingress_id': '.....'
}
response = requests.post(url, headers=headers, json=json_data)
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

I tried to migrate them to ignition script with the following script.

import system
url = '.....'
headers = {
                 'accept': 'application/json',
                 'SY-API-KEY': '.....',
                 'Content-Type': 'application/json',
                  }

json_data = {
    'ingress_id': '.....'
}

response = urllib2.Request(url, headers=headers, data=json_data)
contents = urllib2.urlopen(response).read()
data = system.util.jsonDecode(response)
print(data)

It showed error at the following step:
contents = urllib2.urlopen(response).read()

My question is: How do I realize the following function in ignition?
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

found the problem.

the data type should be converted to json data.

import system
url = '.....'
headers = {
                 'accept': 'application/json',
                 'SY-API-KEY': '.....',
                 'Content-Type': 'application/json',
                  }

json_data = {
    'ingress_id': '.....'
}
json_data = system.util.jsonEncode(json_data)
response = urllib2.Request(url, headers=headers, data=json_data)
contents = urllib2.urlopen(response).read()
data = system.util.jsonDecode(response)
print(data)
  1. How are you using print(data) and that's working, that's python3 syntax, I'm surprised thatis not giving you an error

  2. For HTTP requests it's better to use system.net.httpClient - Ignition User Manual 8.0 - Ignition Documentation

print(data) is used in script console.
In the perspective, it should be system.perspective.print()

what's the format to insert header and data?

I used this:

promise = client.getAsync('****', headers=headers, params=json_data)
response = promise.get()

The response is failed.

url = '.....'
headers = {
    'SY-API-KEY': '.....',
}

json_data = {
    'ingress_id': '.....'
}

response = system.net.httpClient().get(url, headers=headers, data=json_data)
data = response.json()
print(data)

The params argument is for URL parameters. You have data to pass in, so you want the data argument. You also don't need to pass a content type or accept heading manually.

1 Like