Search code examples
pythonfirebasecurlpycurlpyfcm

How to use cURL in python


I want to use this cURL command in (python with pycurl):

curl -X POST --header "Authorization: key=AAAAWuduLSU:APA91bEStixxx" --header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send -d '{"to" : "fC6xEWZwcu0:APA91xxx",  "priority" : "high",  "notification" : {    "body" : "Background Message",    "title" : "BG Title", "sound" : "default"},  "data" : {    "title" : "FG Title",    "message" : "Foreground Message"  }}'

My source code is like this

import pycurl
import re
import io
import json
import requests

data = {"to" : "fC6xEWZwcu0:APA91xxx",  "priority" : "high",  "notification" : {    "body" : "Background Message",    "title" : "BG Title", "sound" : "sound.mp3"},  "data" : {    "title" : "FG Title",    "message" : "Foreground Message"  }}

buffer = io.BytesIO()
c = pycurl.Curl()

c.setopt(c.URL, 'https://fcm.googleapis.com/fcm/send')
c.setopt(c.POST, True)
c.setopt(c.SSL_VERIFYPEER, False)

c.setopt(pycurl.HTTPHEADER, [
    'Content-type:application/json charset=utf-8',
    'Content-Length:0'
    'Authorization: Basic key=AAAAWuduLSU:APA91bEStixxx'
])

c.setopt(c.WRITEDATA, buffer)

'''
c.setopt(pycurl.HTTPBODY, [
    'test:test'

])
'''

print(buffer)
# c.setopt(c.HEADERFUNCTION, header_function)

c.perform()

print('\n\nStatus: %d' % c.getinfo(c.RESPONSE_CODE))
print('TOTAL_TIME: %f' % c.getinfo(c.TOTAL_TIME))

c.close()
body = buffer.getvalue()

print(body)

Solution

  • No need to use curl in Python when you have requests!

    import requests
    import json
    
    post_data = {"to" : "fC6xEWZwcu0:APA91xxx",
                 "priority" : "high",
                 "notification": {"body": "Background Message",
                                  "title": "BG Title",
                                  "sound": "sound.mp3"},
                 "data": {"title": "FG Title",
                          "message": "Foreground Message"}}
    
    header_data = {'Authorization': 'key=AAAAWuduLSU:APA91bEStixxx',
                   'Content-Length': '0',
                   'Content-type': 'application/json'}
    
    r = requests.post('https://fcm.googleapis.com/fcm/send',
                       data = json.dumps(post_data),
                       headers=header_data)
    
    print('\n\nStatus: %d'.format(r.status_code))
    print('TOTAL_TIME: %f'.format(r.elapsed.total_seconds()))
    print(r.text)
    

    Haven't tested this, but it should set you on the right track. I'd also recommend checking out the Requests module docs for more information :-)