curl to Python, Node, PHP: Convert Any curl Command to Code Instantly
Every API documentation page has curl examples. Every developer has spent time manually translating those curl commands into Python, JavaScript, or PHP. This guide breaks down exactly how curl flags map to code in six languages, and shows you how to automate the entire process.
Why curl Commands Are Everywhere
curl is the universal language of HTTP. When Stripe publishes their API docs, the first example is curl. When you debug a webhook with Postman, the export option gives you curl. When a teammate shares a failing request in Slack, it is almost always a curl command.
There is a good reason for this. curl is language-agnostic, available on every operating system, and maps directly to HTTP concepts. A single curl command captures the method, URL, headers, body, authentication, and options in one line. No imports, no boilerplate, no framework opinions.
The problem comes when you need to use that curl command in your actual application. You are writing Python, not bash. Your backend is Node.js, not a terminal. And translating curl flags into library-specific syntax by hand is tedious and error-prone, especially when the command has five headers, a JSON body, and basic auth.
Understanding curl Flags: The Complete Reference
Before converting anything, you need to understand what each curl flag does. Here are the flags you will encounter most often in real-world API work.
-X or --request: The HTTP Method
This sets the HTTP method. If omitted, curl defaults to GET (or POST if you provide data with -d).
curl -X POST https://api.example.com/users
curl -X DELETE https://api.example.com/users/42
curl -X PATCH https://api.example.com/users/42
Most languages have separate methods for each HTTP verb. Python requests has requests.get(), requests.post(), etc. Node fetch uses a method option. PHP curl uses CURLOPT_CUSTOMREQUEST.
-H or --header: Custom Headers
Headers are the most common curl flag. You will see them on almost every API call, setting content type, authorization, and custom metadata.
curl -H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-abc123' \
-H 'Accept: application/json' \
https://api.example.com/data
Each -H flag adds one header. The format is always Name: Value with a colon separator. In code, headers typically become a dictionary or associative array. You can validate your headers and check for security issues with the HTTP Status Codes reference.
-d, --data, and --data-raw: Request Body
The -d flag sends data in the request body. If you use -d without specifying -X, curl automatically uses POST.
curl -X POST https://api.example.com/users \
-H 'Content-Type: application/json' \
-d '{"name":"Alice","role":"admin"}'
The difference between -d and --data-raw is subtle but important. With -d, a value starting with @ is treated as a filename (curl reads the file contents). With --data-raw, the @ is treated literally. In browser-based converters, both behave the same since there is no file system to read from.
For URL-encoded form data, the body looks like query string parameters:
curl -X POST https://example.com/login \
-d 'username=admin&password=secret'
-u or --user: Basic Authentication
The -u flag is a shorthand for HTTP Basic Authentication. curl takes the username:password pair, Base64-encodes it, and sends it as an Authorization: Basic ... header.
curl -u admin:secret123 https://api.example.com/admin
This is equivalent to manually setting the header:
curl -H 'Authorization: Basic YWRtaW46c2VjcmV0MTIz' https://api.example.com/admin
When converting to code, most HTTP libraries have native basic auth support. Python requests has an auth parameter. Node axios has an auth config option. You can encode the credentials yourself with the Base64 Encoder.
-b or --cookie: Sending Cookies
The -b flag attaches cookies to the request. This is useful when testing authenticated endpoints that rely on session cookies rather than token-based auth.
curl -b 'session=abc123; csrf=xyz789' https://example.com/dashboard
In generated code, cookies are typically sent as a Cookie header.
-k or --insecure: Skip SSL Verification
The -k flag tells curl to skip SSL certificate verification. You will use this when hitting internal APIs with self-signed certificates or during local development.
curl -k https://internal.corp.example.com/health
Each language handles this differently. Python requests uses verify=False. Go uses InsecureSkipVerify: true in a TLS config. PHP curl uses CURLOPT_SSL_VERIFYPEER. This should never be used in production. Check your SSL configuration with the SSL Checker instead of disabling verification.
--compressed: Accept Compressed Responses
The --compressed flag tells curl to request compressed responses (gzip, deflate) and automatically decompress them. Most HTTP libraries handle compression transparently, so this flag typically just translates to an Accept-Encoding header.
curl --compressed https://api.example.com/large-dataset
Convert curl Commands Instantly
Stop translating curl flags by hand. Paste any curl command and get production-ready code in Python, Node.js, PHP, Go, Ruby, and Java.
Try the curl ConverterConverting curl to Python (requests)
Python's requests library is the most popular HTTP client in the Python ecosystem. Here is how a typical curl command maps to requests code.
Starting with this curl command:
curl -X POST https://api.example.com/users \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer sk-test-123' \
-d '{"name":"Alice","email":"alice@example.com"}'
The equivalent Python code:
import requests
url = 'https://api.example.com/users'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk-test-123'
}
data = '{"name":"Alice","email":"alice@example.com"}'
response = requests.post(url, headers=headers, data=data)
print(response.status_code)
print(response.json())
The mapping is straightforward. The -X POST becomes requests.post(). Each -H header becomes a key-value pair in the headers dictionary. The -d body becomes the data parameter. If you want requests to auto-serialize a Python dict to JSON, use the json parameter instead of data.
For basic auth with -u, Python requests has a dedicated parameter:
response = requests.get(url, auth=('admin', 'secret123'))
Converting curl to Node.js (fetch and axios)
Node.js has two popular approaches: the built-in fetch API (available since Node 18) and the axios library.
Using fetch
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk-test-123'
},
body: '{"name":"Alice","email":"alice@example.com"}'
});
const data = await response.text();
console.log(response.status);
console.log(data);
The fetch API is clean and maps closely to the curl structure. Method, headers, and body are all properties of the options object. One gotcha: fetch does not reject on HTTP error status codes (like 404 or 500). You need to check response.ok manually.
Using axios
const axios = require('axios');
const config = {
method: 'post',
url: 'https://api.example.com/users',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer sk-test-123'
},
data: '{"name":"Alice","email":"alice@example.com"}'
};
axios(config)
.then(response => {
console.log(response.status);
console.log(response.data);
})
.catch(error => {
console.error(error.message);
});
Axios automatically parses JSON responses and throws on error status codes. For SSL verification skipping, axios supports a custom httpsAgent. If you are working with JWTs in your headers, check out the JWT Decoder to inspect token payloads.
Converting curl to PHP
PHP has a built-in curl extension that maps almost directly to the command-line curl flags. The naming convention is different (constants instead of flags), but the concepts are identical.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.com/users');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Authorization: Bearer sk-test-123'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, '{"name":"Alice","email":"alice@example.com"}');
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo $httpCode . "\n";
echo $response;
The PHP curl extension uses curl_setopt() to set each option. CURLOPT_HTTPHEADER takes an array of header strings (not key-value pairs). CURLOPT_POSTFIELDS sets the request body. For insecure connections, set CURLOPT_SSL_VERIFYPEER to false.
Converting curl to Go
Go's standard library handles HTTP natively through the net/http package. There is no need for third-party libraries.
package main
import (
"fmt"
"io"
"net/http"
"strings"
)
func main() {
body := strings.NewReader(`{"name":"Alice","email":"alice@example.com"}`)
req, err := http.NewRequest("POST", "https://api.example.com/users", body)
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer sk-test-123")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
fmt.Println(resp.StatusCode)
fmt.Println(string(respBody))
}
Go requires more boilerplate than Python or Node, but the mapping is clear. The request body is a Reader (created from a string). Headers are set via req.Header.Set(). For insecure TLS, you configure a custom Transport with InsecureSkipVerify: true.
Real-World Examples
Example 1: Testing a REST API Endpoint
You are integrating with a payment API. The documentation gives you this curl command:
curl -X POST https://api.payments.com/v1/charges \
-u sk_live_abc123: \
-H 'Content-Type: application/json' \
-d '{"amount":2000,"currency":"usd","source":"tok_visa"}'
Notice the trailing colon after sk_live_abc123:. This means the password is empty, which is standard for API key authentication via basic auth. The converter handles this correctly, generating code that passes only the username.
Example 2: Debugging a Webhook
Your webhook endpoint is not processing payloads correctly. You captured the incoming request and want to replay it:
curl -X POST http://localhost:3000/webhooks/stripe \
-H 'Content-Type: application/json' \
-H 'Stripe-Signature: t=1234,v1=abc...' \
-d '{"type":"payment_intent.succeeded","data":{"object":{"id":"pi_123"}}}'
Converting this to your server's language lets you write a test that replays the exact webhook payload. You can use the JSON Formatter to inspect and clean up the payload before writing your test.
Example 3: Monitoring an Internal Health Endpoint
Your internal service uses self-signed certificates. You need to hit the health endpoint from a monitoring script:
curl -k --compressed \
-H 'Accept: application/json' \
-H 'X-Monitor-Source: cron-healthcheck' \
https://internal.service.local:8443/health
The -k flag is critical here. Without it, the request fails because the certificate is not signed by a trusted CA. The converter includes the appropriate SSL verification bypass for each language.
Example 4: Uploading Data with Authentication
You need to push configuration data to a management API that requires both a bearer token and specific content headers:
curl -X PUT https://config.example.com/api/v2/settings \
-H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIs...' \
-H 'Content-Type: application/json' \
-H 'If-Match: "etag-abc123"' \
-b 'region=us-east-1' \
-d '{"max_connections":500,"timeout_ms":30000}'
This command combines multiple features: a PUT method, bearer token auth, content negotiation headers, conditional update with ETag, cookies, and a JSON body. Manually translating this to code takes time and is easy to get wrong. The curl to Code Converter handles all of these flags in a single paste.
Skip the Manual Translation
Paste any curl command from API docs, browser DevTools, or Postman exports. Get clean, copy-ready code in seconds.
Open curl ConverterWhere Do curl Commands Come From?
You will encounter curl commands in several common workflows:
- API documentation - Nearly every REST API provides curl examples as the primary code sample. Stripe, Twilio, GitHub, AWS, and hundreds of others default to curl.
- Browser DevTools - Right-click any network request in Chrome or Firefox DevTools, select "Copy as cURL", and you have a complete curl command including all headers and cookies from your session.
- Postman exports - Postman's "Code" feature exports requests as curl commands, which you can then convert to any language.
- Teammate debugging - When sharing a failing request in Slack or a GitHub issue, curl is the universal format that works for everyone regardless of their language or framework.
- CI/CD pipelines - Shell scripts in CI often use curl for health checks, deployments, and notifications. Converting these to proper code improves maintainability.
Tips for Clean Conversions
A few practical tips to get the best results from any curl to code conversion:
- Remove unnecessary flags first. Browser DevTools exports include many headers you probably do not need (like
sec-ch-ua,sec-fetch-mode, and lengthy cookie strings). Strip them down to the essentials before converting. - Use --data-raw for literal strings. If your payload contains an
@character and you are using-d, it might be interpreted as a file reference. Use--data-rawto be safe. - Watch for line continuations. Multi-line curl commands use backslash (
\) at the end of each line. Most converters handle this, but if you get parse errors, try collapsing the command to a single line first. - Validate your JSON payloads. Before converting, make sure your JSON body is valid. Use the JSON Formatter to check syntax and pretty-print the payload.
- Check for encoded characters. URLs with query parameters may contain encoded characters. Use the URL Encoder to verify and debug URL encoding issues.
Security Considerations
curl commands frequently contain sensitive data: API keys, bearer tokens, passwords, and session cookies. When using any converter tool, make sure it runs client-side in your browser. The SecureBin curl to Code Converter processes everything locally with JavaScript. No curl commands, credentials, or request data are sent to any server.
If you are working with API keys, consider storing them in environment variables rather than hardcoding them in your converted code. Most languages support reading environment variables:
# Python
import os
api_key = os.environ.get('API_KEY')
# Node.js
const apiKey = process.env.API_KEY;
# PHP
$apiKey = getenv('API_KEY');
# Go
apiKey := os.Getenv("API_KEY")
For more on protecting API credentials, read our guide on API key rotation best practices. And if you need to share sensitive curl commands with a teammate, use SecureBin's encrypted paste instead of Slack or email.
Frequently Asked Questions
Can I convert curl commands that contain API keys or passwords?
Yes. The SecureBin curl to Code Converter runs entirely in your browser. No data is sent to any server, so your API keys, tokens, and passwords never leave your device. It is completely safe to paste curl commands containing sensitive credentials.
Which curl flags does the converter support?
The converter supports the most common flags: -X (method), -H (headers), -d/--data/--data-raw (request body), -u (basic auth), -b (cookies), -k (insecure/skip SSL), and --compressed. These cover the vast majority of real-world curl commands.
What is the difference between curl -d and --data-raw?
Both send data in the request body. The -d flag processes @ prefixes as file references (e.g., -d @file.json reads from file.json). The --data-raw flag treats the value literally, so @file.json is sent as the string "@file.json" rather than reading the file. In browser-based converters, both are treated the same since there is no file system access.
How do I convert a curl command with multiple headers?
Use multiple -H flags, one per header. For example: curl -H 'Content-Type: application/json' -H 'Authorization: Bearer token123' -H 'Accept: application/json' https://api.example.com/data. The converter will include all headers in the generated code for every supported language.
Does the converter handle multipart form uploads?
The current version focuses on JSON and URL-encoded form data. Multipart form uploads (curl -F) involve file system access that cannot be fully replicated in a browser-based converter. For multipart uploads, the generated code provides a solid starting point that you can extend with file handling specific to your language.
Ready to Convert?
Paste a curl command, pick a language, copy the code. No signup, no tracking, no server-side processing.
Launch curl ConverterThe Bottom Line
Converting curl commands to application code is one of those small tasks that adds up fast. Every API integration starts with a curl example. Every debugging session produces a curl command. Every code review includes a "how do I call this endpoint" question. Having a reliable converter saves minutes each time, and those minutes compound into hours across a team.
The SecureBin curl to Code Converter handles the translation instantly for Python, Node.js (fetch and axios), PHP, Go, Ruby, and Java. It runs in your browser, keeps your credentials private, and produces clean code you can paste directly into your project.
Related tools: curl Converter, JSON Formatter, JWT Decoder, Base64 Encoder, URL Encoder, HTTP Status Codes, and 70+ more free tools.
Usman has 10+ years of experience securing enterprise infrastructure, managing high-traffic servers, and building zero-knowledge security tools. Read more about the author.