简体   繁体   中英

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?

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

One good resource I've used for converting a cURL request to Python requests is curlconverter . You can enter your cURL request and it will format it for Python requests .

As a side note, it can also convert for PHP and Node.js.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM