1

I am trying to call API from postman but I am getting an error in my console. In the below code, I am trying to decode it and process further according to it.

API- https://localhost:5005/abc/xyz
Method- POST

Data - {"q":"hi"}

server.py

 def request_parameters(request):
    if request.method.decode('utf-8', 'strict') == 'GET':
        return {
            key.decode('utf-8', 'strict'): value[0].decode('utf-8',
                                                           'strict')
            for key, value in request.args.items()}
    else:
        content = request.content.read()
        try:
            return json.loads(content.decode('utf-8', 'strict'))
        except ValueError as e:
            logger.error("Failed to decode json during respond request. "
                         "Error: {}. Request content: "
                         "'{}'".format(e, content))
            raise

Full stacktrace

     Failed to decode json during respond request. Error: Expecting value: line 1 column 1 (char 0). Request content: 'b'''
2019-05-14 18:21:53+0530 [-] Unhandled Error
        Traceback (most recent call last):
          File "C:\Anaconda3\lib\site-packages\twisted\web\server.py", line 258, in render
            body = resrc.render(self)
          File "C:\Anaconda3\lib\site-packages\klein\resource.py", line 210, in render
            d = defer.maybeDeferred(_execute)
          File "C:\Anaconda3\lib\site-packages\twisted\internet\defer.py", line 151, in maybeDeferred
            result = f(*args, **kw)
          File "C:\Anaconda3\lib\site-packages\klein\resource.py", line 204, in _execute
            **kwargs)
        --- <exception caught here> ---
          File "C:\Anaconda3\lib\site-packages\twisted\internet\defer.py", line 151, in maybeDeferred
            result = f(*args, **kw)
          File "C:\Anaconda3\lib\site-packages\klein\app.py", line 128, in execute_endpoint
            return endpoint_f(self._instance, *args, **kwargs)
          File "C:\Anaconda3\lib\site-packages\klein\app.py", line 227, in _f
            return _call(instance, f, request, *a, **kw)
          File "C:\Anaconda3\lib\site-packages\klein\app.py", line 50, in _call
            result = f(*args, **kwargs)
          File "server.py", line 61, in parse
            request_params = request_parameters(request)
          File "server.py", line 22, in request_parameters
            return json.loads(content.decode('utf-8', 'strict'))
          File "C:\Anaconda3\lib\site-packages\flask\json\__init__.py", line 205, in loads
            return _json.loads(s, **kwargs)
          File "C:\Anaconda3\lib\site-packages\simplejson\__init__.py", line 535, in loads
            return cls(encoding=encoding, **kw).decode(s)
          File "C:\Anaconda3\lib\site-packages\simplejson\decoder.py", line 370, in decode
            obj, end = self.raw_decode(s)
          File "C:\Anaconda3\lib\site-packages\simplejson\decoder.py", line 400, in raw_decode
            return self.scan_once(s, idx=_w(s, idx).end())
        simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

script.js

function respond(msg) {
data = {
    query: msg //msg is getting from chatbot
}
fetch(`${url}/conversations/default/respond`, {
    mode: 'no-cors',
    method: 'POST',
    // dataType:'jsonp',
    q: data,
    headers: {
      'Content-Type': 'application/json',
    },

})
sheel
  • 467
  • 8
  • 23
  • 1
    Ok, the error actually occurs on line `return json.loads(content.decode('utf-8', 'strict'))`. According to your source, the value of `content` should have been logged. Can you share it? The error occurs at the beginning, so you are probably trying to decode something which is not in Json format. – Serge Ballesta May 14 '19 at 13:06
  • In content I got this `b'{\n\t"q":"hi"\n\t\n}'` – sheel May 14 '19 at 13:14
  • That's weird, because when I feed that into my Json parser it gives me back `{'q': 'hi'}`. I cannot reproduce, so I cannot help. – Serge Ballesta May 14 '19 at 13:28
  • @SergeBallesta, when I am trying to send request from browser its, is giving me an error and now from postman it working fine. I think you are right it is not in JSON format. In content, now I am getting this `b' '` I have added my front end code above please check it. – sheel May 14 '19 at 13:41
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/193329/discussion-between-sheel-and-serge-ballesta). – sheel May 14 '19 at 13:45
  • 1
    I can confirm that decoding an empty string gives that error. But I cannot help you more because now you must identify why you get an empty string there... – Serge Ballesta May 14 '19 at 13:46
  • 1
    Why are you using `q: data` to init the `fetch` in JS? https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch I think it does not anything . You should use `body: JSON.stringify`: https://stackoverflow.com/questions/29775797/fetch-post-json-data – imposeren May 14 '19 at 13:56

1 Answers1

-1

You can get the content directly in json with request.get_json()

F Blanchet
  • 1,430
  • 3
  • 21
  • 32
  • I tried `request.get_json()` and `request.json()` but got error like this `AttributeError: 'Response' object has no attribute 'json'` – sheel May 14 '19 at 13:15