Search code examples
pythonjsonpostwerkzeug

'Request' object has no attribute 'get_json' Werkzeug


I am unable to print out or read json data from my request. The POST request is application/json and the json sent is valid. Any idea why 'get_json' doesn't exist?

from werkzeug.wrappers import Request, Response
import json

@Request.application
def application(request):
    data = request.get_json(force=True)
    print(data)
    return Response('Data Received')

if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 5000, application)

Replacing request.get_json with request.get_data returns the json as a string (d'{\n"example": "here"\n}')

I've confirmed my Werkzeug installation is up-to-date.


Solution

  • I was able to solve my own issue;

    request doesn't by default have get_json, you need to subclass it and add it yourself.

    Here's an example:

    from werkzeug.wrappers import BaseRequest, Response
    from werkzeug.wrappers.json import JSONMixin
    
    class Request(BaseRequest, JSONMixin):
        '''Allow get_json with Werkzeug'''
        pass
    
    @Request.application
    def application(request):
        data = request.get_json(force=True)
        print(data)
        return Response('Data Received')
    
    def __init__(self):
            if __name__ == '__main__':
                from werkzeug.serving import run_simple
                run_simple('localhost', 5000, application)