How to access data in json and save to a variable in python? flask-api

Asked

Viewed 637 times

1

I am making a very simple Flask Api, I will receive a title and a body in json..

{
"title":"Test",
"body":"test"
}

My app.py class is like this

from flask import Flask, request, jsonify, json

app = Flask(__name__)

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

And I have another class that has a method that gets a title and a body item(title, body). So I’d like to know how to transform this json and take these 2 parameters to call this method.

NOTE: I am not using a database, this program is just to get the json and call the method.

1 answer

2


The method get_json() already treats the json and returns to you the converted object in python:

data = request.get_json()

Here data is already a python dictionary, data['title'] and data['body'] have the data that came in request.

So you can call a method that gets the correct parameters def item(title, body), directly passing each parameter:

item(**data)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.