Search code examples
pythonapipostfalcon

API REST falcon python POST METHOD


I've tried to write an API REST using falcon.

on_get method works well, but when using on_post, I can't get the body of the POST request and I don't know why

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"
}

What am I missing?


Solution

  • at first, use req.media for retrieving data(suggestion).
    second, for the response, use resp.body = json.dumps({"test": "answer"})