0

I want to make a curl to python converter.

curl -X POST -H "data1:value1" -H "data2:value2" -d "{"datapart1":"random1","datapart2":"random2"}" "https://example.com"'

And i want to convert:

import requests

url = 'https://example.com'

data = '{"datapart1":"random1","datapart2":"random2"}'

headers = {'data1': 'value1', 'data2': 'value2'}

r = requests.post(url, data=data, headers=headers)
print(r.text)
Wasi
  • 1
  • 1
  • 1
    Great! Sounds like you want `shlex.split()` to split the `curl` command line to parts like the shell does, and then continue from there. – AKX Feb 24 '22 at 08:28

2 Answers2

0

I think you want this https://formatter.xyz/curl-to-python-converter

you try it that

  • This site submits your curl commands to their server. They could be saving your curl commands. curl commands can contain cookies and other sensitive information if you copied them [from the browser](https://everything.curl.dev/usingcurl/copyas) or someone sent you a command. I wouldn't use this. – Boris Verkhovskiy Aug 05 '22 at 18:42
  • Also, the OP is asking how to implement this himself, not for a website that does it. – Boris Verkhovskiy Aug 05 '22 at 18:51
0

curlconverter.com is a curl -> Python requests converter. It also outputs other languages.

It's implemented in JavaScript (actually TypeScript), so you can use it in your tool if you implement it in JavaScript too (instead of Python) or you can use one of the ways of calling JavaScript code from Python.

Alternatively, it has a command line interface you can call from Python. First, install the command line tool with npm install -g curlconverter then call it from Python with subprocess:

import subprocess

def curl_to_code(command, language='python'):
    return subprocess.run(['curlconverter', '--language', language, '-'], text=True, input=command, capture_output=True).stdout

print(curl_to_code("curl --data helloworld example.com"))

Disclaimer: I contribute to curlconverter.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103