Http json request invalid response

I am trying to query data from a rest API via the anvil.http.request method.
Following the API documentation http://api.3plcentral.com/rels/auth
I have been able to successfully post and receive a response with this code (key has been obfuscated)
def get_tplcdata():
resp = anvil.http.request(url=“https://secure-wms.com/AuthServer/api/Token”,
method=“POST”,
data=’{“grant_type”: “client_credentials”,“tpl”: “{666mytpl555}”,“user_login_id”: “66”}’,
headers= {
“Host”: “secure-wms.com”,
“Content-Type”: “application/json; charset=utf-8”,
“Connection”: “keep-alive”,
“Accept”: “application/json”,
“Accept-Encoding” : “gzip,deflate,sdch”,
“Authorization”: “Basic asdfmykey4321”,
})
print(f"Response MIME type: {resp.content_type}")
print(f"The response body was {resp.get_bytes()}")

and I get this result :
Response MIME type: application/json; charset=utf-8
The response body was b’{“access_token”:“blabla-mytoken0987654321”,“token_type”:“Bearer”,“expires_in”:0,“refresh_token”:null,“scope”:null}’

so far, so good. I need to use the value in access_token as a variable for a future request, so I added the parameter json=True to the http.request. When I do that, it fails with :

HttpErrorStatus: Invalid JSON in response at /libanvil/anvil/http.py, line 51 called from [API3plcentral, line 20](javascript:void(0)) called from [Form1, line 20](javascript:void(0))

The response above looks like good Json to me. Is there something else that I need to do for this to work ?

First, welcome to Anvil!

Second, please can you format your code correctly to make it easier for someone to help you? You need to wrap your code around triple backticks, eg :
```
<code here>
```
so it looks like this :

def get_tplcdata():
  resp = anvil.http.request(url=“https://secure-wms.com/AuthServer/api/Token”,
  method=“POST”,
  etc etc 

Third, this website concurs that your json is indeed not valid : https://freeonlinetools24.com/json-decode
if you paste that result into it.

However, if I manually change all the double quotes into keyboard double quotes, it works. My guess is those double quotes are unicode characters that just look like quotes and they are messing up the json reader.

I would leave out the json=True and instead decode the body yourself and use something like the json library to read the result.

1 Like