Get the data received in a Flask request Ask Question Asked 10 years, 10 months ago Modified 7 months ago Viewed 1.7m times 1192 I want to be able to get the data sent to my Flask app. I’ve tried accessing request.data but it is an empty string. How do you access request data? from flask import request @app.route('/', methods=['GET', 'POST']) def parse_request(): data = request.data # data is empty # need posted data here The answer to this question led me to ask Get raw POST body in Python Flask regardless of Content-Type header next, which is about getting the raw data rather than the parsed data. python flask werkzeug Share edited Apr 7, 2020 at 22:44 davidism 118k2727 gold badges383383 silver badges333333 bronze badges asked May 3, 2012 at 15:31 ddinchev 33k2828 gold badges8585 silver badges130130 bronze badges Add a comment 23 Answers Sorted by: 2090 ![[./resources/python-get-the-data-received-in-a-flask-request-st.resources/svg_2.8.svg]] The docs describe the attributes available on the request object (from flask import request) during a request. In most common cases request.data will be empty because it’s used as a fallback: request.data Contains the incoming request data as string in case it came with a mimetype Flask does not handle. request.args: the key/value pairs in the URL query string request.form: the key/value pairs in the body, from a HTML post form, or JavaScript request that isn’t JSON encoded request.files: the files in the body, which Flask keeps separate from form. HTML forms must use enctype=multipart/form-data or files will not be uploaded. request.values: combined args and form, preferring args if keys overlap request.json: parsed JSON data. The request must have the application/json content type, or use request.get_json(force=True) to ignore the content type. All of these are MultiDict instances (except for json). You can access values using: request.form['name']: use indexing if you know the key exists request.form.get('name'): use get if the key might not exist request.form.getlist('name'): use getlist if the key is sent multiple times and you want a list of values. get only returns the first value. Share edited Sep 22, 2021 at 13:02 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered May 21, 2013 at 7:25 Robert 31.3k88 gold badges3434 silver badges3333 bronze badges Add a comment 281 For URL query parameters, use request.args. search = request.args.get("search") page = request.args.get("page") For posted form input, use request.form. email = request.form.get('email') password = request.form.get('password') For JSON posted with content type application/json, use request.get_json(). data = request.get_json() Share edited Aug 4, 2019 at 20:41 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Aug 12, 2014 at 15:22 Fizer Khan 86k2828 gold badges142142 silver badges152152 bronze badges Add a comment 270 To get the raw data, use request.data. This only works if it couldn’t be parsed as form data, otherwise it will be empty and request.form will have the parsed data. from flask import request request.data Share edited Aug 4, 2019 at 20:38 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered May 3, 2012 at 15:38 clyfish 10.2k22 gold badges3030 silver badges2323 bronze badges Add a comment 160 Here’s an example of parsing posted JSON data and echoing it back. from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/foo', methods=['POST']) def foo(): data = request.json return jsonify(data) To post JSON with curl: curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo Or to use Postman: Share edited Aug 5, 2019 at 14:03 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Nov 16, 2016 at 3:55 Little Roys 5,15333 gold badges2828 silver badges2828 bronze badges Add a comment 72 To get the raw post body regardless of the content type, use request.get_data(). If you use request.data, it calls request.get_data(parse_form_data=True), which will populate the request.form MultiDict and leave data empty. Share edited Aug 4, 2019 at 20:53 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Aug 14, 2015 at 7:29 Xiao 11.9k22 gold badges2828 silver badges3636 bronze badges 1 This should really be upvoted more. We can just request.get\_data() regardless of whether we received form or json data. – [R.S.K](https://stackoverflow.com/users/1081402/r-s-k) [Feb 9, 2022 at 10:30](https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request#comment125595493_32004597) I was looking for this solution – [user582175](https://stackoverflow.com/users/582175/user582175) [May 3, 2022 at 7:23](https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request#comment127387079_32004597) Using `request.get_data()` doesn't work for me when `request.method == 'GET':` I found that `request.args` worked. – [Brad Grissom](https://stackoverflow.com/users/1760405/brad-grissom) [Dec 12, 2022 at 17:25](https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request#comment131967179_32004597) Add a comment 55 If you post JSON with content type application/json, use request.get_json() to get it in Flask. If the content type is not correct, None is returned. If the data is not JSON, an error is raised. @app.route("/something", methods=["POST"]) def do_something(): data = request.get_json() Share edited Aug 4, 2019 at 20:49 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Jul 27, 2015 at 13:06 Amitkumar Karnik 9171515 silver badges2323 bronze badges Add a comment 36 To get request.form as a normal dictionary , use request.form.to_dict(flat=False). To return JSON data for an API, pass it to jsonify. This example returns form data as JSON data. @app.route('/form_to_json', methods=['POST']) def form_to_json(): data = request.form.to_dict(flat=False) return jsonify(data) Here’s an example of POST form data with curl, returning as JSON: $ curl http://127.0.0.1:5000/data -d "name=ivanleoncz&role=Software Developer" { "name": "ivanleoncz", "role": "Software Developer" } Share edited Mar 28, 2020 at 4:52 answered Jun 6, 2018 at 19:54 ivanleoncz 8,60266 gold badges5757 silver badges4848 bronze badges Add a comment 25 Use request.get_json() to get posted JSON data. data = request.get_json() name = data.get('name', '') Use request.form to get data when submitting a form with the POST method. name = request.form.get('name', '') Use request.args to get data passed in the query string of the URL, like when submitting a form with the GET method. request.args.get("name", "") request.form etc. are dict-like, use the get method to get a value with a default if it wasn’t passed. Share edited Aug 4, 2019 at 21:40 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Mar 10, 2019 at 7:32 Ravin Gupta 76377 silver badges1313 bronze badges Add a comment 22 Import request: from flask import request URL query parameters: name = request.args.get("name") age = request.args.get("age") Form Input: name = request.form.get('name') age = request.form.get('age') OR (use indexing if you know the key exists, specify the name of input fields) name = request.form['name'] age = request.form['age'] JSON Data (for content type application/json) data = request.get_json() Share answered May 9, 2021 at 20:03 Murad 9861414 silver badges1313 bronze badges Add a comment 20 To get JSON posted without the application/json content type, use request.get_json(force=True). @app.route('/process_data', methods=['POST']) def process_data(): req_data = request.get_json(force=True) language = req_data['language'] return 'The language value is: {}'.format(language) Share edited Aug 4, 2019 at 20:55 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Mar 25, 2018 at 14:45 Tarik Fojnica 65566 silver badges1515 bronze badges I was facing this issue, didn't send "application/json" in headres while calling the API – [Keval](https://stackoverflow.com/users/7212249/keval) [Jan 18 at 11:37](https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request#comment132628974_49477090) Add a comment 19 You can get request data from request.form for form data, this includes form and file data, request.json and request.get_json for JSON data request.headers for headers request.args to get query params They’re all like a dictionary, use request.form['name'] if you know the key exists, or request.form.get('name') if it is optional. Share edited Jan 18, 2022 at 1:27 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Nov 12, 2021 at 10:45 bkoiki950 22522 silver badges33 bronze badges Add a comment 17 To post JSON with jQuery in JavaScript, use JSON.stringify to dump the data, and set the content type to application/json. var value_data = [1, 2, 3, 4]; $.ajax({ type: 'POST', url: '/process', data: JSON.stringify(value_data), contentType: 'application/json', success: function (response_data) { alert("success"); } }); Parse it in Flask with request.get_json(). data = request.get_json() Share edited Feb 2, 2020 at 17:46 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered May 11, 2018 at 13:58 vaishali KUNJIR 9471111 silver badges99 bronze badges Add a comment 15 The raw data is passed in to the Flask application from the WSGI server as request.stream. The length of the stream is in the Content-Length header. length = request.headers["Content-Length"] data = request.stream.read(length) It is usually safer to use request.get_data() instead. Share edited Aug 4, 2019 at 21:07 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Jul 11, 2016 at 15:46 Daniel 39144 silver badges88 bronze badges Add a comment 14 Here’s an example of posting form data to add a user to a database. Check request.method == "POST" to check if the form was submitted. Use keys from request.form to get the form data. Render an HTML template with a otherwise. The fields in the form should have name attributes that match the keys in request.form. from flask import Flask, request, render_template app = Flask(__name__) @app.route("/user/add", methods=["GET", "POST"]) def add_user(): if request.method == "POST": user = User( username=request.form["username"], email=request.form["email"], ) db.session.add(user) db.session.commit() return redirect(url_for("index")) return render_template("add_user.html") Username Email Share edited Apr 7, 2020 at 22:42 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Oct 11, 2019 at 2:57 Dulangi_Kanchana 1,08499 silver badges2121 bronze badges Add a comment 12 To parse JSON, use request.get_json(). @app.route("/something", methods=["POST"]) def do_something(): result = handle(request.get_json()) return jsonify(data=result) Share edited Aug 4, 2019 at 21:05 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Aug 22, 2017 at 12:46 zhangqy 85377 silver badges1010 bronze badges Add a comment 11 When writing a Slack bot, which is supposed to send JSON data, I got a payload where the Content-Type was application/x-www-form-urlencoded. I tried request.get_json() and it didn’t work. @app.route('/process_data', methods=['POST']) def process_data(): req_data = request.get_json(force=True) Instead I used request.form to get the form data field that contained JSON, then loaded that. from flask import json @ app.route('/slack/request_handler', methods=['POST']) def request_handler(): req_data = json.loads(request.form["payload"]) Share edited Mar 29, 2021 at 14:45 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Sep 24, 2020 at 4:13 Phoebe 12911 silver badge55 bronze badges Add a comment 10 If the body is recognized as form data, it will be in request.form. If it’s JSON, it will be in request.get_json(). Otherwise the raw data will be in request.data. If you’re not sure how data will be submitted, you can use an or chain to get the first one with data. def get_request_data(): return ( request.args or request.form or request.get_json(force=True, silent=True) or request.data ) request.args contains args parsed from the query string, regardless of what was in the body, so you would remove that from get_request_data() if both it and a body should data at the same time. Share edited Aug 4, 2019 at 21:28 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Dec 1, 2018 at 5:04 Paul Gowder 2,34911 gold badge2020 silver badges3535 bronze badges Add a comment 9 If the content type is recognized as form data, request.data will parse that into request.form and return an empty string. To get the raw data regardless of content type, call request.get_data(). request.data calls get_data(parse_form_data=True), while the default is False if you call it directly. Share edited Aug 4, 2019 at 21:11 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Aug 21, 2018 at 22:52 Zavec 18522 silver badges1010 bronze badges Add a comment 5 When posting form data with an HTML form, be sure the input tags have name attributes, otherwise they won’t be present in request.form. @app.route('/', methods=['GET', 'POST']) def index(): print(request.form) return """ """ ImmutableMultiDict([('txt3', 'text 3')]) Only the txt3 input had a name, so it’s the only key present in request.form. Share edited Aug 4, 2019 at 21:21 davidism 118k2727 gold badges383383 silver badges333333 bronze badges answered Aug 20, 2018 at 15:45 freezed 1,22911 gold badge1717 silver badges3434 bronze badges Add a comment 5 @app.route('/addData', methods=['POST']) def add_data(): data_in = mongo.db.Data id = request.values.get("id") name = request.values.get("name") newuser = {'id' : id, 'name' : name} if voter.find({'id' : id, 'name' : name}).count() > 0: return "Data Exists" else: data_in.insert(newuser) return "Data Added" Share answered Jul 21, 2020 at 10:54 Divyani Singh 49188 silver badges1616 bronze badges Add a comment -2 I just faced the same need. I have to save information in case of any unexpected situation. So, I use the following formula: Info = "%s/%s/%s" % (request.remote_addr, repr(request), repr(session)) repr(request) will give a string representation of the basic information. You could add user-agent data with: request.headers.get(‘User-Agent’) I also save the session continent as it could contain valuable information Share edited Dec 27, 2021 at 15:09 answered Dec 27, 2021 at 13:10 Rapace-bleu 3966 bronze badges Add a comment -4 request.data This is great to use but remember that it comes in as a string and will need iterated through. Share edited Oct 9, 2020 at 12:55 SecretAgentMan 2,82677 gold badges2020 silver badges4141 bronze badges answered Oct 9, 2020 at 8:29 James 5311 silver badge77 bronze badges 8 Already answered a lot of times, besides iterating over a string makes no sense. – [Cloudkollektiv](https://stackoverflow.com/users/7950592/cloudkollektiv) [Oct 9, 2020 at 12:59](https://stackoverflow.com/questions/10434599/get-the-data-received-in-a-flask-request#comment113668375_64276517) Add a comment -4 Try - > from flask import request @app.route('/', methods=['GET', 'POST']) def parse_request(): if request.method == 'POST': data = request.form.get('data') Share answered Oct 13, 2021 at 14:11 Nimit Gupta 12344 bronze badges Add a comment ![[./resources/python-get-the-data-received-in-a-flask-request-st.resources/svg_26.svg]] Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation requirement helps protect this question from spam and non-answer activity. Not the answer you’re looking for? Browse other questions tagged python flask werkzeug or ask your own question. The Overflow Blog ![[./resources/python-get-the-data-received-in-a-flask-request-st.resources/svg_27.svg]] What our engineers learned building Stack Overflow (Ep. 547) ![[./resources/python-get-the-data-received-in-a-flask-request-st.resources/svg_28.svg]] Moving up a level of abstraction with serverless on MongoDB Atlas and AWS sponsored post Featured on Meta We’ve added a “Necessary cookies only” option to the cookie consent popup [Temporary policy: ChatGPT is banned](https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned?cb=1) [The rowname and columnname tags are being burninated](https://meta.stackoverflow.com/questions/420433/the-rowname-and-columnname-tags-are-being-burninated?cb=1) [Plagiarism flag and moderator tooling has launched to Stack Overflow!](https://meta.stackoverflow.com/questions/423749/plagiarism-flag-and-moderator-tooling-has-launched-to-stack-overflow?cb=1) [A/B testing related questions within the answers list (experiment has graduated)](https://meta.stackoverflow.com/questions/423143/a-b-testing-related-questions-within-the-answers-list-experiment-has-graduated?cb=1) Linked 84How to obtain values of request variables using Python and Flask 35How to get form data in Flask? 32Flask - Bad Request The browser (or proxy) sent a request that this server could not understand 12How check if value exists in request POST? 11Retrieve text from textarea in Flask 11Question marks in Flask Urls for routing 4Python Flask not receiving AJAX post? 5view multipart form request parameter values using flask 6PUT request to upload a file not working in Flask 5How to handle missing parameters in URL with Flask/Python 3 See more linked questions Related 4257Finding the index of an item in a list 12537What does the “yield” keyword do in Python? 3715How do I get the current time? 5084Accessing the index in ‘for’ loops 2681How do I get the last element of a list? 3297“Least Astonishment” and the Mutable Default Argument 3584What is the difference between str and repr? 2233How do I get the number of elements in a list (length of a list) in Python? 660Configure Flask dev server to be visible across the network 156Get raw POST body in Python Flask regardless of Content-Type header Hot Network Questions Is it logical to seek revenge? What do ‘flat-chested’ and ‘unromantic’ mean when speaking of a house? Is light only emitted by atoms? i.e are they the only source of light in the universe? How to model an irregular pentagon pattern? How can I signal to others on my flight that I want to make friends and chat? What’s the relation between two symmetry groups, if one has all the symmetry of the other and some more? How can I say “take your time” in German? What is neoliberalism? Does the NEC allow a sub panel to be powered by a generator and an automatic transfer switch? Why do single band 10 meter radios exist? Reduce a MeijerG to elementary function Where do I hook up a speaker in this schematic? Why is the ICC focusing on the transfer of war orphans to Russia rather than Russia’s much more obvious crimes in Ukraine? rsync the file ab How many geodesics exist between two spacetime events? Do black holes have a size? How can a DM communicate to the players that subtlety is needed in a mystery adventure? ChatGPT is aware of today’s date Moving magnet frequency over a coil Does a literary or film allusion, done for effect, require a citation? How can I make square and triangular rings? How to quickly generate rectangles in place of text Is it permitted to fly a 737-800 with one pilot? Which Preposition is Used Concerning Paul’s Body in Galatians 6:17? ![[./resources/python-get-the-data-received-in-a-flask-request-st.resources/svg_29.svg]] Question feed