1

I'm catching a POST request from requests to flask-rest and I keep getting a 400 error code (Bad Request).

Requests Part:

def send_data(asset_id, data1, data2, data3):
    global _server_api
    headers = {'content-type': 'application/json'}
    complete_url = _server_api + asset_id
    payload = {'d1': data1,'d2': data2,'d3': data3}
    response = requests.post(complete_url, data=json.dumps(payload), headers=headers)

Flask Part:

from flask.ext.restful.representations.json import output_json
from flask import Flask, request
from flask_restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
assets = {}
class Broker(Resource): 
   def post(self, asset_id):
       assets[asset_id] = dict()
       data1 = request.form['d1']
       data2 = request.form['d2']
       data3 = request.form['d3']
       assets[asset_id]['d1'] = request.form['d1']
       assets[asset_id]['d2'] = request.form['d2']
       assets[asset_id]['d3'] = request.form['d3']
       collector(asset_id, data1, data2, data3) #<--- writes to DB
       return {asset_id: assets[asset_id]}

api.add_resource(Broker, '/api-v1.0/add/<string:asset_id>', methods=['PUT', 'POST', 'GET'])

Error Code:

{u'status': 400, u'message': u'Bad Request'}

I keep getting a 400 Error code when the requests part makes the call to the API.

When changing the request.form to request.get_json I get a error as below .

TypeError: 'instancemethod' object has no attribute '__getitem__'

Any help would be appreciated.

1 Answer 1

2

You're sending a JSON request, but the app expects a form. Instead of request.form use request.get_json() in the app.

Sign up to request clarification or add additional context in comments.

2 Comments

I get the following error when I change all to request.get_jason() in the app. TypeError: 'instancemethod' object has no attribute 'getitem'
I was using the get_jason() incorrectly and see it needs to be captured and the paramrs extracted using standard dict method. .myvar['myparam']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.