cURL to Python Turn any curl command into Python requests code.
Turn any curl command into Python requests code.POSThttps://api.example.com/v1/customers
HEADERS · 2
AuthorizationBearer sk_t••••••→ API_TOKEN
Content-Typeapplication/json
BODY · JSON
{
"email": "ada@example.com",
"name": "Ada Lovelace",
"metadata": {
"plan": "pro",
"seats": 3
}
}Pythonrequests
import os
import requests
headers = {
"Authorization": f"Bearer {os.environ['API_TOKEN']}",
}
payload = {
"email": "ada@example.com",
"name": "Ada Lovelace",
"metadata": {
"plan": "pro",
"seats": 3,
},
}
response = requests.post(
"https://api.example.com/v1/customers",
headers=headers,
json=payload,
)
response.raise_for_status()
data = response.json()24 linesReads secrets with os.environ
How curl maps to requests
The arguments you'll see in the code.
- json=A JSON body becomes json=payload. requests sets the Content-Type header for you.
- data= · files=Form fields go in data=, and -F file uploads become files= with an open file.
- auth= · timeout=-u becomes auth=(user, password). -m 30 becomes timeout=30 — always set one.
- raise_for_status()Turns 4xx and 5xx responses into exceptions, the way curl's --fail does.
Questions
The short answers.
requests or httpx?
The code uses requests. httpx has almost the same API, plus async — swap the import and it mostly just works.
Many calls to the same API?
Create a requests.Session() and reuse it. It keeps the connection open and shares headers.
What about -k?
That's verify=False. We leave it out on purpose; only add it for a local test server.
Where do tokens and passwords go?
With “Secrets as env variables” on, they're read with os.environ, so they stay out of your code.
How are file uploads sent?
Each -F file=@path becomes an open file in files=, which requests streams from disk. A ;type= in the curl command is passed along as the file's content type.