Mounarajan Mounarajan - 26 days ago 9
reST (reStructuredText) Question

How to make curl post request from python

I am trying to make a post request using curl in python but the below script throws error

import os

first_name1 = "raj"
last_name1 = "kiran"
full_name = "raj kiran"
headline = "astd"
location1 = "USA"
current_company1 = "ss"

curl_req = 'curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'.format(first_name1,last_name1,current_company1,headline,location1,full_name)

os.popen(curl_req)


Error:

SyntaxError: invalid syntax


How to make above program work?

Answer Source

The problem in your code is the quotes. Change it to:

curl_req = '''curl -X POST -H "Content-Type: application/json" -d '{"first_name":"{0}","last_name":"{1}","current_company":"{2}","title":"{3}","campus":"","location":"{4}","display_name":"{5}","find_personal_email":"true"}' http://localhost:8090'''.format(first_name1,last_name1,current_company1,headline,location1,full_name)

But, as mentioned in the comments, requests will always be a better choice.

Requests syntax:

import requests
post_data = { 
   # all the data you want to send 
}
response = requests.post('http://localhost:8090', data=post_data)
print response.text