How to send POST request using flask.redirect?

Question:

I’m trying to create a flask service in which I want to send the data coming from one request.form to another url in json format, Please can anyone help me to achieve this?

redirect(url_for('any_method'), json = json.dumps(my_form_dict))

When I try to execute the above code I’m getting following error:

TypeError: redirect() got an unexpected keyword argument 'json' The above is the error here.

Answers:

Your problem is that you are passing too much arguments to the redirect function. It only expects three parameters, location, code, and Response. If you want to pass extra parameters, use the Flask url_for method:

redirect(url_for('any_method', json=form_json))

Note the difference, you were passing the url_for and extra fields as two parameters. In my version, I’ve added the extra fields in the url_for, so redirect only receives one parameter.

Answered By: josepdecid

It is not possible to redirect POST requests.
More info is here.

Answered By: Andrejs Cainikovs

You can redirect POST requests using 307 status code.
Use:

redirect(url_for('any_method', json=json.dumps(my_form_dict)), code=307)

For more information refer to this answer:
Make a POST request while redirecting in flask

Answered By: ReemRashwan

I used the requests package to redirect a GET request to the POST one.
The trick is using flask.make_response() to make a new Resposne object.
In my scenario, the last response is an HTML text, so I get text as a response.

from flask import request, make_response
import requests

@app.route('/login', methods=['GET'])
def login():
    data = {"data": request.args['data']}
    redirect_response = requests.post('https://my-api/login', json=data).text
    return make_response(redirect_response, 302)
Answered By: Pedram A. Keyvani
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.