Home > Back-end >  Post requests in python vs curl
Post requests in python vs curl

Time:01-22

Can someone please suggest the correct syntax for calling the below using python?

curl "https://sometest.api.token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id={client_id}&client_secret={client_secret}"

My attempt:

import requests
import json

credentials='1111'
secret='2222'

url = 'https://sometest.api.token'
body = {'client_credentials':credentials,'client_secret':secret}
headers = {'Content-type': 'application/x-www-form-urlencoded'}

r = requests.post(url, data=json.dumps(body), headers=headers)

CodePudding user response:

Due to documentation, if you want to send some form-encoded data, you simply pass a dictionary to the data argument.

So you have to try:

import requests
import json

credentials='1111'
secret='2222'

url = 'https://sometest.api.token'
body = {'client_credentials':credentials, 'client_secret':secret}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}

r = requests.post(url, data=body, headers=headers)

And also your parameters in python code are different from parameters in curl, maybe you have to check it.

  •  Tags:  
  • Related