Conversion of curl to Python Requests

Viewed 40057

I'm trying to convert the following working request in curl to a python request (using Requests).

curl --data 'query={"tags":["test1","test2"]}' http://www.test.com/match

(I've used a fake url but the command does work with the real url)

The receiving end (ran in Flask) does this:

@app.route("/match", methods=['POST'])
def tagmatch():
    query = json.loads(request.form['query'])
    tags = query.get('tags')
    # ... does stuff ...
    return json.dump(stuff)

In curl (7.30), ran on Mac OS X (10.9) the command above properly returns a JSON list that's filtered using the tag query.

My Python script is as follows, it returns a 400 Bad Request error.

import requests

payload = {"tags":["test1", "test2"]}
# also tried  payload = 'query={"tags":["test1","test2"]}'
url = 'http://www.test.com/match'

r = requests.post(url, data=payload)

if __name__=='__main__':
     print(r.text)
7 Answers

Save your life

A simpler approach would be:

  1. Open POSTMAN
  2. Click on the "import" tab on the upper left side.
  3. Select the Raw Text option and paste your cURL command.
  4. Hit import and you will have the command in your Postman builder!

Hope this helps!

credit: Onkaar Singh

Try to use uncurl library. It is pretty nice to do its job. I've tried it.

u = uncurl.parse(
        "curl -X GET 'https://mytesturl.com/' -H  'accept: application/json' -H  'Authorization: 1234567890'")
    print(u)

It prints,

requests.get("https://mytesturl.com/",
    headers={
        "Authorization": "1234567890",
        "accept": "application/json"
    },
    cookies={},
)
Related