0

im having trouble forming a proper response using Flask.requests.json

@app.route("/slack/post", methods=["POST"])
def post_response_to_slack():
    try:
        body = request.json

the output using request.data is:

 b'{"phone":"+1XXXXXXXXX",\n"body":"This\nDoesn\'t\nWork",\n"slack_tag":"slack_bot"\n}'

when i try request.json i get 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

i suspect its something to do with incorrect handling of the new lines but im not sure where im going wrong

the header content type is Content-Type: application/json

for some more context without line breaks it works:

b'{"phone":"+1XXXXXXXX",\n"body":"This works ",\n"slack_tag":"slack_bot"\n}'

with request.json returning:

{'phone': '+1XXXXXXXXX', 'body': 'This works ', 'slack_tag': 'slack_bot'}

my guess is i need to change the \n into \\n but im not sure how to do that if its coming in as a request

relevant: How do I handle newlines in JSON?

bigalbunyan
  • 73
  • 2
  • 7

1 Answers1

0

You're right. If you're using request.json it will try to put it into that format, and you can't just put \n between them, that's why you're getting the 400 error. Can I ask why you need these line breaks?

  • the payload being parsed is from a texting application through Twilio, so if someone puts a line break in their text it throws an error currently. the only other way i can think of getting this info is parsing the ```request.data``` string – bigalbunyan Jan 18 '21 at 03:47
  • Good idea. Just parse it with request.data and handle the line breaks with some code. – Jonas Möller Jan 19 '21 at 01:35