Converting cURL commands to code is one of the most common tasks in API development. You find a working cURL example in API documentation, test it in your terminal, and then need to translate it into your application's programming language. This guide shows you how to convert cURL to JavaScript (fetch and axios), Python (requests), Go, PHP, and Node.js with practical examples for real-world API calls. Try our free cURL converter to generate code instantly.
Try our free cURL to Code Converter.
Understanding cURL Command Syntax
cURL (Client URL) is a command-line tool for transferring data using various network protocols. It is the de facto standard for testing HTTP APIs because it is available on virtually every operating system and provides fine-grained control over requests. When API documentation provides examples, they are almost always in cURL format.
A cURL command consists of the curl binary followed by a URL and optional flags that control the request method, headers, body, authentication, and other parameters. Understanding these flags is the key to accurate conversion to any programming language.
The most important cURL flags for API calls are: -X (request method), -H (header), -d (data/body), -u (basic auth), -F (form data/file upload), -b (cookies), -k (skip TLS verification), and -L (follow redirects). Each of these maps to specific options in HTTP client libraries.
cURL Flags Reference
Here are the most commonly used cURL flags and what they mean for code conversion:
| Flag | Long Form | Purpose | Example |
|---|---|---|---|
-X | --request | HTTP method | -X POST |
-H | --header | Request header | -H "Content-Type: application/json" |
-d | --data | Request body | -d '{"key":"value"}' |
-u | --user | Basic auth | -u user:password |
-F | --form | Multipart form data | -F "file=@photo.jpg" |
-b | --cookie | Send cookies | -b "session=abc123" |
-o | --output | Save to file | -o response.json |
-L | --location | Follow redirects | -L |
-k | --insecure | Skip TLS verification | -k |
-v | --verbose | Show request/response details | -v |
cURL to JavaScript: fetch and axios
JavaScript fetch API
The fetch API is built into modern browsers and Node.js 18+. It is the standard way to make HTTP requests in JavaScript. Here is how common cURL patterns translate to fetch:
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
// JavaScript fetch equivalent
const response = await fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_TOKEN",
},
body: JSON.stringify({
name: "Alice",
email: "alice@example.com",
}),
});
const data = await response.json();
console.log(data);
// cURL: curl -X GET "https://api.example.com/users?page=1&limit=10" \
// -H "Accept: application/json"
// fetch GET with query parameters
const params = new URLSearchParams({ page: "1", limit: "10" });
const res = await fetch(`https://api.example.com/users?${params}`, {
headers: { Accept: "application/json" },
});
// cURL: curl -u admin:secret123 https://api.example.com/admin
// fetch with Basic Auth
const credentials = btoa("admin:secret123");
const authRes = await fetch("https://api.example.com/admin", {
headers: { Authorization: `Basic ${credentials}` },
});JavaScript axios
axios is a popular HTTP client library that works in both browsers and Node.js. It provides a cleaner API than fetch with built-in JSON parsing, interceptors, and request cancellation:
import axios from "axios";
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
// axios automatically sets Content-Type for objects
const { data } = await axios.post(
"https://api.example.com/users",
{ name: "Alice", email: "alice@example.com" },
{
headers: { Authorization: "Bearer YOUR_TOKEN" },
timeout: 10000, // 10 second timeout
}
);
// cURL: curl -X PUT https://api.example.com/users/123 \
// -H "Content-Type: application/json" \
// -d '{"name":"Alice Updated"}'
const updated = await axios.put(
"https://api.example.com/users/123",
{ name: "Alice Updated" }
);
// cURL: curl -X DELETE https://api.example.com/users/123
await axios.delete("https://api.example.com/users/123");cURL to Python: requests Library
Python's requests library is the most popular HTTP client with an intuitive API. Install with pip install requests. cURL commands translate very naturally to requests:
import requests
# cURL: curl -X POST https://api.example.com/users \
# -H "Content-Type: application/json" \
# -H "Authorization: Bearer YOUR_TOKEN" \
# -d '{"name":"Alice","email":"alice@example.com"}'
response = requests.post(
"https://api.example.com/users",
json={"name": "Alice", "email": "alice@example.com"},
headers={"Authorization": "Bearer YOUR_TOKEN"},
timeout=10,
)
data = response.json()
print(data)
# cURL: curl -u admin:secret123 https://api.example.com/admin
response = requests.get(
"https://api.example.com/admin",
auth=("admin", "secret123"),
)
# cURL: curl -X POST https://api.example.com/upload \
# -F "file=@document.pdf" \
# -F "description=My document"
with open("document.pdf", "rb") as f:
response = requests.post(
"https://api.example.com/upload",
files={"file": ("document.pdf", f, "application/pdf")},
data={"description": "My document"},
)
# cURL: curl -X GET "https://api.example.com/search?q=python&page=1"
response = requests.get(
"https://api.example.com/search",
params={"q": "python", "page": 1},
)
# Error handling
response = requests.post("https://api.example.com/data", json=payload)
response.raise_for_status() # Raises HTTPError for 4xx/5xxcURL to Go: net/http Package
Go's standard library net/http package provides everything needed for HTTP requests. The conversion is more verbose than Python but gives you full control:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
func createUser() error {
payload := map[string]string{
"name": "Alice",
"email": "alice@example.com",
}
body, _ := json.Marshal(payload)
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("POST",
"https://api.example.com/users",
bytes.NewBuffer(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer YOUR_TOKEN")
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
fmt.Println(string(respBody))
return nil
}cURL to PHP: cURL Extension and Guzzle
PHP has a built-in cURL extension that closely mirrors the command-line cURL tool, plus modern alternatives like Guzzle:
<?php
// cURL: curl -X POST https://api.example.com/users \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer YOUR_TOKEN" \
// -d '{"name":"Alice","email":"alice@example.com"}'
// PHP cURL extension (built-in)
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://api.example.com/users",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode([
"name" => "Alice",
"email" => "alice@example.com"
]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer YOUR_TOKEN"
],
CURLOPT_TIMEOUT => 10,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($response, true);
print_r($data);
// PHP Guzzle (modern alternative)
// composer require guzzlehttp/guzzle
use GuzzleHttp\Client;
$client = new Client(["timeout" => 10]);
$response = $client->post("https://api.example.com/users", [
"json" => ["name" => "Alice", "email" => "alice@example.com"],
"headers" => ["Authorization" => "Bearer YOUR_TOKEN"],
]);
$data = json_decode($response->getBody(), true);Common API Call Patterns
Most API calls fall into a few common patterns. Here are the cURL commands and their multi-language equivalents:
GET with query parameters: The simplest pattern. Query parameters in cURL are part of the URL.
POST with JSON body: The most common API mutation. Always set Content-Type: application/json.
Bearer token authentication: Used by most modern APIs (OAuth 2.0, JWT). The token goes in the Authorization header.
File upload (multipart/form-data): Uses -F in cURL. Each language has its own way to construct multipart bodies.
Best Practices for cURL to Code Conversion
Always set Content-Type headers explicitly: cURL with -d defaults to application/x-www-form-urlencoded. Most APIs expect application/json. Always include -H "Content-Type: application/json" in your cURL command and the corresponding header in your code.
Handle errors properly: cURL exits with a non-zero status on errors. In code, check HTTP status codes (4xx/5xx) and implement retry logic for transient failures (429, 503).
Use environment variables for secrets: Never hardcode API keys or tokens. Use process.env.API_KEY (Node.js), os.environ["API_KEY"] (Python), or os.Getenv("API_KEY") (Go).
Set timeouts: cURL has --connect-timeout and --max-time. Always set timeouts in your HTTP client to avoid hanging requests.
Use HTTPS in production: Never use -k (insecure) in production code. Configure proper TLS certificates instead.
Parse response bodies correctly: Check the response Content-Type before parsing. Use .json() (fetch), .json() (requests), or json.Unmarshal (Go) as appropriate.
Consider rate limiting: Add delays between requests and respect Retry-After headers. Implement exponential backoff for retries.
Related tools: JSON Formatter for formatting API responses, JWT Decoder for inspecting authentication tokens, and URL Encoder/Decoder for query parameters.
cURL ConverterJSON FormatterJWT DecoderURL Encoder/Decoder
Frequently Asked Questions
How do I convert a cURL command to JavaScript fetch?
Map cURL flags to fetch options: -X POST becomes method: "POST", -H becomes entries in the headers object, -d becomes the body parameter (use JSON.stringify() for JSON), and -u user:pass becomes a Base64-encoded Authorization: Basic header. Our free cURL converter tool automates this process.
What is the difference between -d and -F in cURL?
-d (--data) sends data as application/x-www-form-urlencoded or raw text. It is used for JSON payloads with -H "Content-Type: application/json". -F (--form) sends data as multipart/form-data, which is required for file uploads. In code, -d maps to setting the request body directly, while -F maps to FormData or multipart body construction.
How do I handle cURL basic authentication in Python?
cURL's -u user:password maps directly to the auth parameter in Python requests: requests.get(url, auth=("user", "password")). The library handles Base64 encoding and the Authorization header automatically. For bearer tokens, use headers={"Authorization": "Bearer TOKEN"}.
Can I convert cURL to multiple programming languages at once?
Yes! Our free cURL to Code converter at DevToolBox parses any cURL command and generates equivalent code in JavaScript (fetch and axios), Python (requests), Go, PHP, Ruby, and more. Just paste your cURL command and select your target language.
How do I convert a cURL command with file upload to code?
cURL file uploads use -F "file=@filename.jpg". In JavaScript, use FormData with formData.append("file", fileBlob). In Python, use requests.post(url, files={"file": open("filename.jpg", "rb")}). In Go, use multipart.NewWriter. Each language has its own multipart body construction API.
Converting cURL to code is a fundamental API development skill. Understanding cURL flags and how they map to HTTP client libraries in JavaScript, Python, Go, and PHP enables you to quickly integrate any API. Use our free online cURL converter to automate the conversion, and follow the best practices in this guide for production-ready API client code.
Convert cURL commands to any programming language with our free tool.
Related Developer Tools and Guides
- cURL Converter - Convert cURL commands to any programming language
- JSON Formatter - Format and validate JSON API responses
- JWT Decoder - Decode and inspect JWT authentication tokens
- URL Encoder/Decoder - Encode query parameters and URLs
- Base64 Encoder/Decoder - Encode Basic Auth credentials
- JSON to TypeScript - Generate types from API responses
- JSON to Go - Generate Go structs from API responses
- JSON to Python - Generate Python dataclasses from JSON
- HTTP Status Codes - Reference for all HTTP response codes
- cURL Cheat Sheet - Complete cURL command reference
- REST API Best Practices - Design patterns for APIs