0

How on earth do I get the post data from a flask app using blueprints and flask-restfull? why so hard?

In my views.py file

 api.add_resource(register, '/api/driver/register')

In my resource file:

from flask_restful import fields, marshal_with, reqparse, Resource
class register(Resource):
    def post(self):
        ACCESS MY POST DATA!!!!!!!!!!!!!
        return 'omg' 



curl -H "Content-Type: application/json" -X POST -d '{"f":"xyz","u":"xyz"}' http://0.0.0.0:5000/api/driver/register
Tampa
  • 75,446
  • 119
  • 278
  • 425

2 Answers2

0

Here is an adaptation of your example. It looked like you are on the right track, based on your imports. My example simply takes in 2 JSON parameters, email and mobile, and echos them back in JSON format. You can refer to the values for processing and business logic using args['email'] and args['mobile'].

from flask_restful import fields, marshal_with, reqparse, Resource
class register(Resource):
    def post(self):
        reqparse = reqparse.RequestParser()
        reqparse.add_argument('email', type=str)
        reqparse.add_argument('mobile', type=int)
        args = reqparse.parse_args()
        response = {'email': args['email'], 'mobile': args['mobile']}
        response_fields = {'email': fields.String, 'mobile': fields.Integer}
        return marshal(response, response_fields), 200
Kelly Keller-Heikkila
  • 2,544
  • 6
  • 23
  • 35
0

This is the way I'd do.

from flask_restful import fields, marshal_with, reqparse, Resource


class Register(Resource):

    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('field_data_one', type=str, required=True, location='json')
        self.reqparse.add_argument('field_data_two', type=str, required=True, location='json')
        ...

    def post(self):
        args = self.reqparse.parse_args()

        obj = {
            'field_data_one': args['field_data_one'],
            'field_data_two': args['field_data_two']
        }

        return {'omg': obj}, 201

        # ACCESS MY POST DATA!!!!!!!!!!!!!
        # return 'omg'
Sebastian S
  • 807
  • 6
  • 15