sending post request in flask

13,554

First fix the error:

You need to change this:

res = requests.post('https://fcm.googleapis.com/fcm/send', json=json_string)

to this:

res = requests.post('https://fcm.googleapis.com/fcm/send', data=json_string)

The error you are getting states that requests.post cannot accept an argument named json, but it accepts a keyword argument named data, which can be in json format.

Then add your headers:

If you want to send custom headers with the requests module, you can do it as follows:

headers = {'your_header_title': 'your_header'}
# In you case: headers = {'content-type': 'application/json'}
r = requests.post("your_url", headers=headers, data=your_data)

To sum everything up:

You need to fix your json formatting up a bit. A full solution will be:

json_data = {
    "data":{
        'key': app.config['FCM_APP_TOKEN']
    }, 
    "notification":{
        'title': 'Wyslalem cos z serwera', 
        'body': 'Me'
    }, 
    "to": User.query.filter_by(id=2).first().fcm_token
}

headers = {'content-type': 'application/json'}
r = requests.post(
    'https://fcm.googleapis.com/fcm/send', headers=headers, data=json.dumps(json_data)
)
Share:
13,554
demoo
Author by

demoo

Updated on June 14, 2022

Comments

  • demoo
    demoo about 2 years

    I am trying to send post request in flask.

    I'd like to send json object with Content-Type: application/json set as a header.

    I'm doing this with requests module as follows:

    json_fcm_data = {"data":[{'key':app.config['FCM_APP_TOKEN']}], "notification":[{'title':'Wyslalem cos z serwera', 'body':'Me'}], "to":User.query.filter_by(id=2).first().fcm_token}
    json_string = json.dumps(json_fcm_data)
    print json_string
    res = requests.post('https://fcm.googleapis.com/fcm/send', json=json_string)
    

    But this gives me:

    TypeError: request() got an unexpected keyword argument 'json'

    Any advices on how to fix this?