How to Get Posted Json in Flask

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.

Get json from request flask

You are sending form encoded data, not JSON. Just setting the content-type doesn't turn your request into JSON. Use json= to send JSON data.

response = requests.post(url, json={"user": user,"pass": password})

Retrieve the data in Flask with:

data = request.get_json()

Get POST request body as JSON of array as root node in flask-restful

Currently reqparse will handle only JSON objects as body (source: will fail on any other object except dict and MultiDict), and not any other type. You'll have to grab the request object directly for your needs.

from flask import request
from flask_restful import Resource

class CustomRange(Resource):
def post(self, start: int, end: int):
args = request.json
# rest of your code

How to save a JSON post request with a Flask server?

Use Python's logging facility. An example code below, used from Logging to a file and your snippet shared above.

import logging
from flask import Flask, request

logging.basicConfig(filename='requests.log', level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
if request.method == 'POST':
request_data = request.get_json()
logging.info(request_data)

if __name__ == '__main__':
logging.info("Running application with local development server!")
app.run()

The above code will log your requests with timestamps to a file and append to the file every time a new request is made.

Flask app: Post json to server for use in a different REST API

Use the Fetch API to send the data.

In the following example, the data is converted into a JSON-compliant character string and sent to the server via POST.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<button id="click">Click</button>
<table id="my-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td>
<td>Trousers</td>
<td>9.99</td>
</tr>
<tr>
<td>002</td>
<td>Shirt</td>
<td>19.99</td>
</tr>
<tr>
<td>003</td>
<td>Shoes</td>
<td>49.99</td>
</tr>
</tbody>
</table>

<script type="text/javascript">
(() => {
const tableToJSON = (tableElem) => {
const tableRows = Array.from(tableElem.rows);
const tableHead = Array.from(tableRows[0].cells).map(cell => {
return cell.innerHTML.toLowerCase().replace(/ /g,'_')
});
return tableRows.slice(1).map(row => {
const rowData = {}
Array.from(row.cells).forEach((cell, i) => {
return rowData[tableHead[i]] = cell.innerHTML;
});
return rowData;
});
};

const btnElem = document.getElementById('click');
btnElem.addEventListener('click', (evt) => {
const tableElem = document.getElementById('my-table');
const tableData = tableToJSON(tableElem);

// Post JSON data to the server.
const url = '/data';
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(tableData)
}).then(resp => resp.json())
.then(data => console.log(data));
});
})();
</script>
</body>
</html>

Then you can request and process the data on the server using request.get_json(). The response from the server is a simple JSON object that was converted with jsonify.

from flask import Flask
from flask import render_template, request, jsonify

app = Flask(__name__)
app.secret_key = 'your secret here'

@app.route('/', methods=['GET'])
def index():
return render_template('index.html')

@app.route('/data', methods=['POST'])
def data():
data = request.get_json()
print(data)
return jsonify(success=True)

Flask request.get_json() returning None when valid json data sent via post request

It's request.json it will return a dictionary of the JSON data. To get a value you use request.json.get('value_name'). So your route will be like this

#TODO
@application.route('/test', methods=['GET', 'POST'])
def test():
data = request.json
print("data is " + format(data))
return redirect(url_for('index'))

How to get AJAX posted JSON in flask?

It looks like you didn't specify the content type of your post request look what is said in the official documentation:

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

you need also to serialize you cars object to json object .

you can do something like this :

function doWork() {
// ajax the JSON to the server
$.ajax({
type: 'POST',
url: '/receiver',
data: JSON.stringify (cars),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
// stop link reloading the page
event.preventDefault();
}

Flask receiving Post Json

Just passing a content-type header of JSON doesn't actually make the data itself into JSON. You either need to do that yourself, or tell jQuery to do so.

$.ajax({
url: 'http://127.0.0.1:5000/api/saveannotation',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({'sess_id' : $('#sessionid_area').val(),
'annotations': JSON.parse(annotations)}),
success: function(data) { alert(data.status); }
});

Now your data will be in JSON format and you can get it as a Python dict with request.get_json().

receive in flask json converted and form data

A data transfer can only conform to one format. This formatting is either an encoding for a form or corresponds to JSON formatting.

You can still send the data within one request.
Either you add the JSON-formatted data as a field to the form, or you convert the form data into a JSON structure.

With the first variant, it is necessary to read the JSON data manually on the server side. You can use the python json library for this. For the latter, the framework does this work.

A third option is to transfer the file within the form and simply read it on the server side.

Whichever option you choose, don't forget to validate the inputs.

In the following example, all form data is converted to JSON and sent to the server. I shortened the code a bit for clarity.

The version of adding JSON formatted data to the form data should be self-explanatory.

I think the best solution is to read the file server side.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Read CSV to JSON</title>
</head>
<body>
<form name="my-form" method="post" enctype="" enctype="multipart/form-data">
<input type="text" name="name" />
<!-- ... -->
<input type="file" name="csv" allow="text/csv" />
<input type="submit" />
</form>

<script type="text/javascript">
((uri) => {

function readCSV(file, delim=',') {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = reject;
reader.onload = (evt) => {
resolve(evt.target.result.split(/\r\n|\n/).map(line => line.split(delim)));
};
reader.readAsText(file);
});
}

function serialize(formData) {
const data = {};
for (const [k, v] of formData) data[k] = v;
return data;
}

// Register a listener for submit events and suppress the default behavior of the form.
const form = document.querySelector('form[name="my-form"]');
form.addEventListener('submit', async evt => {
evt.preventDefault();

if(!evt.target.csv.files.length) {
alert('No file selected.');
return;
}

const file = evt.target.csv.files[0];
const formData = new FormData(evt.target);
formData.delete('csv');
// Conversion of the form data into an object.
const data = serialize(formData);
// Reading and converting the file into a list of objects.
// Adding the list to the previous object.
data['csv'] = await readCSV(file, ',')
.then(csv => {
const head = ['time', 'yaw', 'pitch', 'roll', 'heading', 'ax',
'ay', 'az', 'gx', 'gy', 'gz', 'mx', 'my', 'mz'];
return csv.map(row => {
let r = {};
row.forEach((col, i) => r[head[i]] = Number(col));
return r;
});
});

// Sending the JSON data to the server.
fetch(uri, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(resp => resp.json())
.then(data => console.log(data));
});

})({{ url_for('.data') | tojson }});
</script>
</body>
</html>
from flask import Flask
from flask import (
jsonify,
render_template,
request,
)

app = Flask(__name__)

@app.route('/')
def index():
return render_template('index.html')

@app.route('/data', methods=['POST'])
def data():
data = request.json
print(data)
return jsonify(success=True)


Related Topics



Leave a reply



Submit