Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I was trying to write an API REST using falcon.The on_get() function operates properly, but when using on_post(), am not able to get the body of the POST call:

class ProfileUpdate(object):

    def on_post(self, req, resp):

        data = json.load(req.stream)

        print(data)

        resp.body = {"test": "answer"}

        resp.status = falcon.HTTP_200

        return resp

def setup_profile():

    app = falcon.API()

    profile_update = ProfileUpdate()

    app.add_route('/profiles', profile_update)

    return app

I get the following error

Traceback (most recent call last):

  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 135, in handle

    self.handle_request(listener, req, client, addr)

  File "/usr/local/lib/python3.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request

    respiter = self.wsgi(environ, resp.start_response)

  File "/usr/local/lib/python3.7/site-packages/falcon/api.py", line 318, in __call__

    body, length = self._get_body(resp, env.get('wsgi.file_wrapper'))

  File "/usr/local/lib/python3.7/site-packages/falcon/api.py", line 820, in _get_body

    body = body.encode('utf-8')

AttributeError: 'dict' object has no attribute 'encode'

I am using Postman to test the API. I tried using the following body in POSTMAN (raw -> JSON):

{

"email":"test"

}

1 Answer

0 votes
by (108k points)

See, firstly you need to use:

 req.media 

For retrieving data(suggestion)and secondly, for getting the response, use:

 resp.body = json.dumps({"test": "answer"})

If you are newbie and want to explore more about Python, then learn Python from the below video tutorial:

Related questions

Browse Categories

...