Back to Blog

How to Convert cURL Commands to Python requests

The cURL command-line tool is ubiquitous in API documentation and debugging. However, when you need to integrate that API call into your Python application, you must convert the cURL syntax into a Python requests script. This guide covers how to map cURL flags to the requests library.

Basic GET Request

cURL:

curl https://api.example.com/users

Python:

import requests

response = requests.get('https://api.example.com/users')
print(response.json())

Adding Headers (-H)

Headers are passed using the headers dictionary in Python.

cURL:

curl -H"Authorization: Bearer my_token"\
 -H"Accept: application/json"\
 https://api.example.com/data

Python:

import requests

headers = {
 'Authorization': 'Bearer my_token',
 'Accept': 'application/json'
}

response = requests.get('https://api.example.com/data', headers=headers)

Sending JSON Data (-d / --data)

When sending JSON, use the json parameter in requests.post(). This automatically sets the Content-Type: application/json header.

cURL:

curl -X POST https://api.example.com/users \
 -H"Content-Type: application/json"\
 -d '{"name":"Alice","role":"admin"}'

Python:

import requests

json_data = {
 'name': 'Alice',
 'role': 'admin'
}

response = requests.post('https://api.example.com/users', json=json_data)

Form Data and Multipart Uploads (-F)

For file uploads or form data, use the files or data parameters.

cURL:

curl -X POST https://api.example.com/upload \
 -F"file=@/path/to/image.jpg"\
 -F"description=Profile photo"

Python:

import requests

files = {
 'file': open('/path/to/image.jpg', 'rb')
}
data = {
 'description': 'Profile photo'
}

response = requests.post('https://api.example.com/upload', files=files, data=data)

Basic Authentication (-u)

cURL:

curl -u username:password https://api.example.com/protected

Python:

import requests

response = requests.get('https://api.example.com/protected', auth=('username', 'password'))

Error Handling Patterns

Always check for HTTP errors in your requests:

import requests

try:
 response = requests.get('https://api.example.com/data', timeout=5)
 response.raise_for_status() # Raises an HTTPError for bad responses (4xx and 5xx)
 data = response.json()
except requests.exceptions.HTTPError as errh:
 print(f"HTTP Error: {errh}")
except requests.exceptions.ConnectionError as errc:
 print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
 print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
 print(f"Something went wrong: {err}")

Disabling SSL Verification (-k / --insecure)

If you are testing against a local server with a self-signed certificate, you can disable SSL verification (not recommended for production).

Python:

response = requests.get('https://localhost:8443/test', verify=False)

Want to convert your commands instantly? Try our cURL to Python/JavaScript/Go Converter.