Python-flask extracting values from a POST request to REST API

Question:

I am trying to extract values from a JSON payload by POST request:

Question 1:
What is a better way to get the data?

First Way?

@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        test = request.data
        return test

or Second Way?

@app.route('/login', methods=['POST'])
def login():
    if request.method == 'POST':
        test = json.loads(request.json)
        return test

Question 2:
How do I get a specific value?

Given the json payload is:

{ "test": "hello world" }

I tried doing code below, but does not work.

#way1
return request.data["test"]

#error message: TypeError: string indices must be integers, not str

#way2
test["test"]

#error message: TypeError: expected string or buffer
Asked By: edmamerto

||

Answers:

If you are posting JSON to a flask endpoint you should use:

request.get_json()

A very important API note:

By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter

Meaning… either make sure the mimetype of the POST is application/json OR be sure to set the force option to true

A good design would put this behind:

request.is_json like this:

@app.route('/post/', methods=['POST'])
def post():
    if request.is_json:
        data = request.get_json()
        return jsonify(data)
    else:
        return jsonify(status="Request was not JSON")
Answered By: abigperson

Request.get_json() parses the incoming JSON request data and returns it. By default this function will return None if the mimetype is not application/json but this can be overridden by the force parameter.

Request.get_json(force=False, silent=False, cache=True) 

Example:

import flask
from flask import request, jsonify

app = flask.Flask(__name__)
app.config["DEBUG"] = True

@app.route("/login",  methods = ['POST'])
def login():
    req = request.get_json()
    return "Hello " + req['username']

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)
Answered By: Codemaker