Daniel Fridman
Daniel Fridman

Reputation: 204

Sending post request with both data and JSON parameters

I am trying to send a post request with both data and JSON fields, such as:

my_df = pd.read_csv('test.csv')
pickled = pickle.dumps(my_df)
pickled_b64 = base64.b64encode(pickled)

my_name = "my_csv_name.csv"

r = requests.post('http://localhost:5003/rcvdf', data = pickled_b64, json= {"name": my_name})

Notice that pickled_b64 is of type 'bytes'.

But on the other end, I get only the data and no JSON at all:

@api.route('/rcvdf', methods=['POST'])
def test_1():
    data_pickeled_b64_string = request.data
    json_data = request.json #This is None

Is it even possible to pass two variables in such a way?

--edit

Solution

thanks to the comments I tried different approach - and passed the variable by headers:

Sending Side:

my_name = "my_csv.csv"

r = requests.post('http://localhost:5003/rcvdf', data=pickled_b64, headers={"name": my_name})

Receiving Side:

@app.route('/rcvdf', methods=['POST'])
def rcvdf():
    data_pickeled_b64_string = request.data
    name = request.headers['name']

Upvotes: 3

Views: 1263

Answers (2)

DRPK
DRPK

Reputation: 2091

An Alternative method:

Since base64 encoding has ASCI format you can convert it to simple string object.

Then you can do it by embedding your pickled_b64 in your json data:

import base64, request


pickled_b64 = str(base64.b64encode("hello world".encode()), encoding="utf-8")
json_data = {"Pickled_B64": pickled_b64, "Name": "my_csv_name.csv"}
send_request = requests.post('http://localhost:5003/rcvdf', json=json_data)
print(send_request.json())

and on your backend side:

from flask import make_response, jsonify

@api.route('/rcvdf', methods=['POST'])
def test_1():
    pickled_b64 = request.json.get('Pickled_B64', None)
    name = request.json.get('Name', None)
    reserve_dict = {"Status": "Got it", "name": name, "pickled_b64": pickled_b64}
    reserve_response = make_response(jsonify(reserve_dict), 200)
    return reserve_response

Upvotes: 1

SergiyKolesnikov
SergiyKolesnikov

Reputation: 7795

requests.post(url, json=payload) is just a shortcut for requests.post(url, data=json.dumps(payload))

Note, the json parameter is ignored if either data or files is passed.

docs

So, no, it is not possible to pass both data and json parameters.

Upvotes: 5

Related Questions