Flask Testing a put request with custom headers

Sheshank Kodam picture Sheshank Kodam · Jan 14, 2017 · Viewed 8.1k times · Source

Im trying to test a PUT request in my Flask app, using flasks test client. Everything looks good to me but i keep getting 400 BAD request.

I tried the same request using POSTMAN and I get the response back.

Here is the code

 from flask import Flask 
 app = Flask(__name__) 
 data = {"filename": "/Users/resources/rovi_source_mock.csv"}
 headers = {'content-type': 'application/json'}
 api = "http://localhost:5000/ingest"
 with app.test_client() as client:
    api_response = client.put(api, data=data, headers=headers)
 print(api_response)

Output

Response streamed [400 BAD REQUEST]

Answer

Martijn Pieters picture Martijn Pieters · Jan 14, 2017

You do need to actually encode the data to JSON:

import json

with app.test_client() as client:
    api_response = client.put(api, data=json.dumps(data), headers=headers)

Setting data to a dictionary treats that as a regular form request, so each key-value pair would be encoded into application/x-www-form-urlencoded or multipart/form-data content, if you had used either content type. As it is, your data is entirely ignored instead.