Pythonista
Pythonista

Reputation: 117

Convert cURL command Into Python using requests

I am trying to convert the following cULR command into Python:


curl --location --request POST 'api.datamyne.com/frontend/REST/application' \
--header 'Content-Type: application/json' \
--data-raw '{
  "token": "boKnofR06mzldz5eL00ARwa3B9winzpn",
  "idApp":44
}'

I have the following Python code, but does not seem to work. Any idea how to include the raw data into into the request?

import requests

headers = {
    'Content-Type': 'application/json',
    'token': 'boKnofR06mzldz5eL00ARwa3B9winzpn',
    'idApp': '44'
}

response = requests.get('http://api.datamyne.com/frontend/REST/applications', headers=headers)

print(response.content)

Upvotes: 3

Views: 6789

Answers (1)

Michael
Michael

Reputation: 130

So in your python example you have called request.get().

If you call request.post() it will instead become a POST request.

as for adding it to the body, you could try a body variable:

data =  {
    'token': 'boKnofR06mzldz5eL00ARwa3B9winzpn',
    'idApp': '44'
}

response = requests.post('http://api.datamyne.com/frontend/REST/applications',
                          headers=headers,
                          data = data)

Update: This still fails because of an incorrectly formatted body.

to fix this i imported the json package and wrote:

#load string into a json object
data =  json.loads('{"token": "boKnofR06mzldz5eL00ARwa3B9winzpn", "idApp": 44 }')

# json.dumps outputs a json object to a string.
response = requests.post('https://api.datamyne.com/frontend/REST/application', headers=headers, data=json.dumps(data))

Upvotes: 7

Related Questions