FmtDev
Langue
Retour au blog
26 mars 2026

How to Convert cURL to Python Requests (With Examples)

Convert any cURL command to Python requests code. Includes a cheat sheet, 5 real examples, and an instant converter tool.

How to Convert cURL to Python Requests (With Examples)

You have a working cURL command and you need to convert cURL to Python requests right now. You might have copied it from an API documentation site, a coworker, or your browser's network tab. You can approach this in two different ways. You can use an instant converter tool or you can learn the manual mapping between cURL flags and Python arguments. Both methods are covered completely in this post.

Instant Conversion: Convert cURL to Python Automatically

If you are in a rush to ship a feature, you can skip the manual work entirely. Paste your command directly into our cURL to Python converter. Keep this link bookmarked. Paste your cURL command into the tool and you get Python requests code instantly.

Here is a before and after example of exactly what the tool does for you.

Before:

curl -X POST https://api.example.com/users -H "Content-Type: application/json" -H "Authorization: Bearer token123" -d '{"name": "John", "email": "john@example.com"}'

After:

import requests

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer token123"
}
json_data = {
    "name": "John",
    "email": "john@example.com"
}
response = requests.post("https://api.example.com/users", headers=headers, json=json_data)

If you just need the exact answer quickly, that tool handles it perfectly. Read on to understand the exact mapping and how to rewrite these commands yourself.

The Convert cURL to Python Requests Cheat Sheet

Google loves useful reference tables. Here is your definitive cheat sheet for daily development. This table maps every common cURL flag to its exact Python requests equivalent.

| cURL Flag | Python requests Equivalent | Example | |---|---|---| | -X POST | method="POST" or requests.post() | requests.post(url) | | -H "Header: value" | headers={"Header": "value"} | headers={"Content-Type": "application/json"} | | -d '{"data"}' | data='{"data"}' or json={"data"} | json={"name": "John"} | | -u user:pass | auth=("user", "pass") | auth=("admin", "secret") | | -b "cookie=val" | cookies={"cookie": "val"} | cookies={"session": "abc"} | | -L | allow_redirects=True (default) | already default behavior | | -k | verify=False | verify=False | | -x proxy:port | proxies={"https": "proxy:port"} | proxies={"https": "http://proxy:8080"} | | --connect-timeout 10 | timeout=10 | timeout=10 |

Keep this table handy when you need to translate curl to python manually. It covers the vast majority of API testing python scenarios you will encounter in your career.

5 Real-World Ways to Convert cURL to Python

Sometimes you just need to see real code to understand the mechanics. Here are five practical examples of converting a curl command to python. Make sure you run pip install requests in your terminal before running any of this code.

1. Simple GET Request

This is the absolute simplest case you will encounter. It is a basic HTTP request with no headers, no cookies, and no data payload. GET is the default HTTP method for both tools.

cURL:

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

Python:

import requests

response = requests.get("https://api.example.com/users")

You do not need to specify the -X GET method explicitly. Both cURL and the requests library default to GET automatically to fetch data.

2. POST with JSON Body

Modern APIs practically run entirely on JSON data. When you convert a curl post to python requests, you usually deal with JSON payloads updating server state.

cURL:

curl -X POST https://api.example.com/users -H "Content-Type: application/json" -d '{"name": "John"}'

Python:

import requests

response = requests.post(
    "https://api.example.com/users", 
    json={"name": "John"}
)

Notice how we can drop the Content-Type header entirely in Python. When you use the built-in json= parameter, requests sets the Content-Type: application/json header automatically. You do not need to provide the exact -H equivalent in your headers dictionary. Use our JSON Formatter if you need to debug messy payloads before converting them.

3. Request with Authentication Header

Secure APIs require proper authentication before they return sensitive data. You typically pass a security token via an HTTP header.

cURL:

curl https://api.example.com/data -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."

Python:

import requests

headers = {
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiIs..."
}
response = requests.get("https://api.example.com/data", headers=headers)

Any -H flag maps directly to the headers dictionary in Python safely. You can include as many custom headers as your API requires in this single dictionary object. If you are working with Bearer tokens and need to inspect the payload, you can decode that JWT using our JWT Decoder tool locally.

4. POST with Form Data

Older APIs and user login endpoints often expect traditional form-encoded requests. The difference between data= (form encoded) and json= (JSON body) is the single most common mistake in conversion workflows.

cURL:

curl -X POST https://api.example.com/login -d "username=admin&password=secret"

Python:

import requests

form_data = {
    "username": "admin", 
    "password": "secret"
}
response = requests.post("https://api.example.com/login", data=form_data)

Using data= explicitly tells the requests library to encode the dictionary as application/x-www-form-urlencoded. This behavior perfectly matches the default behavior of the cURL -d flag. Both approaches achieve the exact same network request.

5. File Upload

Uploading files requires Multipart form data encoding. The cURL syntax uses the -F flag to designate a file transfer operation.

cURL:

curl -X POST https://api.example.com/upload -F "file=@photo.jpg"

Python:

import requests

files = {
    "file": open("photo.jpg", "rb")
}
response = requests.post("https://api.example.com/upload", files=files)

The cURL -F flag maps directly to the files= parameter in Python. You must open the file in binary read mode by passing rb for the upload to execute correctly. The requests library automatically handles all the complex multipart boundary logic for you.

Common Mistakes When You Convert cURL to Python

Translating curl to python code is usually straightforward. However, these specific edge cases trap developers constantly. Double-check your implementations against these rules.

Mistake 1: Using data= When You Need json=

If your cURL command has -H "Content-Type: application/json" and uses -d with a JSON string, you must be extremely careful. Use the json= argument in your Python code, not data=.

# DO THIS:
requests.post(url, json={"name": "John"})

# DO NOT DO THIS:
requests.post(url, data='{"name": "John"}')

The json= argument auto-serializes your Python dictionary AND sets the Content-Type header smoothly. The data= argument only sends a raw string and does NOT set the correct Content-Type header automatically.

Mistake 2: Forgetting to Parse the JSON String

The cURL -d flag takes a raw text string wrapped in quotes like \'{"name": "John"}\'. The Python json= parameter requires a native Python dictionary structure.

# DO THIS:
payload = {"name": "John"}

# DO NOT DO THIS:
payload = '{"name": "John"}'

Do not wrap your Python dictionary in extra quotes. If you send a statically quoted string to the json= parameter, requests will double-encode your payload. This triggers immediate syntax errors on the backend server. If your converted code fails because of malformed JSON from the API, check out our guide on fixing "Unexpected token..." errors to understand how to debug the response.

Mistake 3: Shell Escaping Issues

You often copy cURL commands from API documentation sites or Postman into your Python scripts. These commands frequently contain shell-specific escaping rules to deal with terminal interpreters.

You will often see unexpected backslashes, messy quote conflicts, and interpreted dollar signs. These shell escapes do not translate to Python code syntax. For example, pasting \"Content-Type\" directly into a Python dictionary causes a SyntaxError. You absolutely must strip all shell escaping formatting before converting the command.

Mistake 4: Ignoring the Response

A cURL command dumps the network response straight to your terminal screen automatically. In Python scripts, you have to extract the data payload explicitly. You need to know how to properly handle the response object.

import requests

response = requests.get("https://api.example.com/users")

# Check if the request succeeded (returns True if 200-299)
if response.ok:
    # Parse JSON automatically into a dictionary
    data = response.json()
    
    # Or get the raw text string response
    raw_text = response.text
    
    # View response headers directly
    server_headers = response.headers

If you run response.json() and the server returned an HTML error page, Python throws a decode error. Always check response.status_code or response.ok before trying to parse the JSON output.

When to Use a Converter Tool vs Manual Conversion

You should ultimately understand both methods perfectly when working with APIs. Each method provides specific benefits mapping into your daily workflow.

Use a converter tool when you have a massive cURL command filled with dozens of headers, cookies, and authentication flags. When you simply need working code incredibly fast, pasting it into our cURL to Python converter instantly saves you twenty minutes of tedious typing.

Use manual conversion when you need to understand exactly what each piece of the request does. Manual translation is strictly required when you are building a reusable SDK function. You must parameterize specific variables instead of hardcoding exact static text.

The core mapping principles between cURL execution and Python requests execution are highly consistent and easily learnable.

For quick one-off script conversions, use the automated tool instead of taxing your brain. Paste any cURL command into our cURL to Python converter at /curl-to-python and get working Python code instantly.

Outil associé

Prêt à utiliser l'outil Our Secure Tool ? Toute l'exécution est locale.

Ouvrir Our Secure Tool