DevToolBox無料
ブログ

cURL to Code 変換オンラインガイド:JavaScript、Python、Go、PHP

14分by DevToolBox

cURL is the universal language of HTTP requests. Every API documentation you encounter, every Stack Overflow answer about HTTP calls, and every debugging session with a backend service eventually involves a cURL command. But cURL commands are meant for the terminal, not your application code. This comprehensive guide shows you how to convert cURL commands to production-ready code in JavaScript (fetch and axios), Python (requests and httpx), Go, PHP, Ruby, and Rust. You will learn every major cURL flag and its equivalent in each programming language, how to handle authentication patterns including Bearer tokens, Basic auth, and API keys, how to upload files with multipart/form-data, manage cookies and custom headers, and automate cURL conversion in your CI/CD pipeline. Whether you are integrating a third-party API, debugging a microservice, or building an API client library, mastering cURL-to-code conversion is an essential developer skill.

TL;DR

  • cURL is a command-line tool for HTTP requests. Converting cURL to code means mapping flags like -X, -H, -d, -u, and -F to your language HTTP client.
  • JavaScript: Use fetch() for browser/Node.js 18+ or axios for richer features like interceptors and automatic JSON parsing.
  • Python: The requests library provides the cleanest mapping from cURL. httpx adds async support and HTTP/2.
  • Go, PHP, Ruby, Rust all have standard library HTTP clients. Each maps cURL flags differently but follows the same pattern.
  • Always use environment variables for API keys and tokens. Never hardcode secrets in converted code.
  • Use our free online cURL to Code converter to instantly generate production-ready code from any cURL command.

Key Takeaways

  • cURL flags map predictably to HTTP client options: -X sets the method, -H sets headers, -d sets the body, -u sets Basic auth, -F sets multipart form data.
  • fetch() is the modern standard for JavaScript HTTP requests, built into browsers and Node.js 18+. axios remains popular for its interceptors, automatic transforms, and cleaner error handling.
  • Python requests is the gold standard for simplicity. httpx extends it with async/await and HTTP/2 support for high-performance applications.
  • Go net/http is verbose but gives complete control. PHP has both the native curl extension and the modern Guzzle library. Ruby has Net::HTTP and Faraday. Rust uses reqwest.
  • Authentication patterns (Bearer, Basic, API key) translate consistently across all languages. Always store credentials in environment variables.
  • Multipart file uploads (-F flag) require FormData in JavaScript, files parameter in Python, multipart.Writer in Go, and CURLFile in PHP.
  • Automated cURL conversion in CI/CD pipelines helps maintain API client libraries and integration tests across polyglot codebases.
Try our free cURL to Code converter

1. What Is cURL and Why Convert to Code?

cURL (Client URL) is a command-line tool and library for transferring data with URLs. Created by Daniel Stenberg in 1998, it supports over 25 protocols including HTTP, HTTPS, FTP, SFTP, SMTP, and more. It is installed by default on macOS, most Linux distributions, and Windows 10+, making it the most universally available HTTP client in existence.

API documentation almost always provides examples in cURL format because it is language-agnostic and universally understood. When you test an API endpoint in the terminal with cURL and confirm it works, the next step is translating that working command into your application programming language.

Converting cURL to code involves mapping each cURL flag and option to the equivalent construct in your target language HTTP client library. The URL becomes the request target, -X becomes the method, -H entries become headers, -d becomes the request body, and authentication flags become auth configuration.

This conversion process is mechanical but error-prone when done manually. Missing a header, misformatting the body, or incorrectly encoding authentication credentials can cause subtle bugs that are hard to diagnose. That is why automated conversion tools save significant development time.

2. cURL Flags Reference: The Complete Mapping

Understanding cURL flags is the foundation of accurate conversion. Here is every commonly used flag, what it does, and how it maps to code.

-X / --request

-X / --request: Sets the HTTP method (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS). If omitted, cURL defaults to GET. When -d is present without -X, cURL uses POST automatically. In code, this maps to the method parameter or option in every HTTP client.

-H / --header

-H / --header: Adds a request header. Can be specified multiple times for multiple headers. Format: -H "Name: Value". In code, headers are typically collected into a key-value object or map. Common headers: Content-Type, Authorization, Accept, User-Agent.

-d / --data

-d / --data: Sends request body data. Implies POST method if -X is not set. Sends as application/x-www-form-urlencoded by default. For JSON payloads, always pair with -H "Content-Type: application/json". In code, this maps to the body or data parameter.

--data-raw

--data-raw: Same as -d but does not interpret @ as a file reference. Use this when your data literally starts with @. In most code conversions, -d and --data-raw are treated identically since HTTP clients do not have the @ file convention.

-F / --form

-F / --form: Sends multipart/form-data. Used for file uploads and mixed content. Format: -F "field=value" or -F "file=@/path/to/file". In code, this maps to FormData (JavaScript), files parameter (Python), multipart.Writer (Go), or CURLFile (PHP).

-u / --user

-u / --user: Sets Basic HTTP authentication. Format: -u username:password. cURL Base64-encodes the credentials and adds the Authorization: Basic header. In code, most libraries have a dedicated auth parameter that handles encoding automatically.

-b / --cookie

-b / --cookie: Sends cookies with the request. Format: -b "name=value; name2=value2". In code, cookies are typically set via a Cookie header or a dedicated cookie jar. Some libraries like Python requests have a cookies parameter.

-k / --insecure

-k / --insecure: Skips TLS certificate verification. Useful for testing against self-signed certificates but dangerous in production. In code, this maps to verify=False (Python), rejectUnauthorized: false (Node.js), or TLSClientConfig with InsecureSkipVerify (Go). Never use in production.

-L / --location

-L / --location: Follows HTTP redirects (3xx responses). Most HTTP client libraries follow redirects by default, so this flag often requires no code equivalent. In Python requests, set allow_redirects=True (already the default). In Go, the default client follows redirects.

-o / --output

-o / --output: Saves the response body to a file. In code, this means writing the response body to a file using fs.writeFile (Node.js), open().write() (Python), os.Create (Go), or file_put_contents (PHP).

-v / --verbose

-v / --verbose: Shows detailed request and response information including headers. In code, enable logging or use request/response interceptors for equivalent debugging output.

--connect-timeout

--connect-timeout: Maximum time to wait for the connection to be established. In code, set connection timeout via the HTTP client configuration. Always set timeouts to avoid hanging requests.

--max-time / -m

--max-time / -m: Maximum total time for the operation including transfer. Maps to total request timeout in code. Combined with --connect-timeout, this gives you fine-grained timeout control.

--compressed

--compressed: Requests compressed response (gzip, deflate, br) and automatically decompresses. Most modern HTTP clients handle compression automatically, but you may need to set Accept-Encoding headers explicitly in some cases.

3. Converting cURL to JavaScript (fetch & axios)

Using the fetch API

The fetch API is the modern standard for making HTTP requests in JavaScript. It is built into all modern browsers, Node.js 18+, Deno, and Bun. fetch is Promise-based and provides a clean, low-level interface for HTTP requests.

A simple GET request with headers. cURL: curl -H "Authorization: Bearer TOKEN" -H "Accept: application/json" https://api.example.com/users

const response = await fetch("https://api.example.com/users", {
  headers: {
    "Authorization": "Bearer " + process.env.API_TOKEN,
    "Accept": "application/json"
  }
});
const data = await response.json();

A POST request with JSON body. cURL: curl -X POST -H "Content-Type: application/json" -d '{"name":"John","email":"john@example.com"}' https://api.example.com/users

const response = await fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    name: "John",
    email: "john@example.com"
  })
});
const data = await response.json();

A file upload with multipart/form-data. cURL: curl -F "file=@photo.jpg" -F "description=Profile photo" https://api.example.com/upload

const formData = new FormData();
formData.append("file", fileBlob, "photo.jpg");
formData.append("description", "Profile photo");

const response = await fetch("https://api.example.com/upload", {
  method: "POST",
  body: formData
  // Note: Do NOT set Content-Type header manually.
  // fetch sets it automatically with the correct boundary.
});
// Basic auth: curl -u user:password https://api.example.com/data
const credentials = btoa("user:password");
const response = await fetch("https://api.example.com/data", {
  headers: {
    "Authorization": "Basic " + credentials
  }
});

Using axios

axios is a popular HTTP client library that works in both browsers and Node.js. It provides automatic JSON parsing, request/response interceptors, request cancellation, and a cleaner API for common patterns. Install with npm install axios.

// GET with auth header
const { data } = await axios.get("https://api.example.com/users", {
  headers: {
    "Authorization": "Bearer " + process.env.API_TOKEN
  }
});
// POST with JSON body
const { data } = await axios.post("https://api.example.com/users", {
  name: "John",
  email: "john@example.com"
});
// axios automatically sets Content-Type: application/json
// and serializes the object to JSON
// File upload with FormData
const formData = new FormData();
formData.append("file", fs.createReadStream("photo.jpg"));
formData.append("description", "Profile photo");

const { data } = await axios.post("https://api.example.com/upload", formData, {
  headers: formData.getHeaders()
});
// Basic auth with axios built-in support
const { data } = await axios.get("https://api.example.com/data", {
  auth: {
    username: "user",
    password: "password"
  }
});

4. Converting cURL to Python (requests & httpx)

Using the requests library

Python requests is the most popular HTTP client in the Python ecosystem. Its API maps almost perfectly to cURL flags, making conversion straightforward. Install with pip install requests.

# GET with auth header
# curl -H "Authorization: Bearer TOKEN" https://api.example.com/users
import requests
import os

response = requests.get(
    "https://api.example.com/users",
    headers={"Authorization": f"Bearer {os.environ['API_TOKEN']}"},
)
data = response.json()
# POST with JSON body
# curl -X POST -H "Content-Type: application/json" \
#   -d '{"name":"John"}' https://api.example.com/users
response = requests.post(
    "https://api.example.com/users",
    json={"name": "John", "email": "john@example.com"},
)
data = response.json()
# File upload (multipart/form-data)
# curl -F "file=@photo.jpg" -F "desc=Profile" https://api.example.com/upload
with open("photo.jpg", "rb") as f:
    response = requests.post(
        "https://api.example.com/upload",
        files={"file": ("photo.jpg", f, "image/jpeg")},
        data={"desc": "Profile"},
    )
# Basic auth
# curl -u user:password https://api.example.com/data
response = requests.get(
    "https://api.example.com/data",
    auth=("user", "password"),
)
# Cookies
# curl -b "session=abc123; theme=dark" https://api.example.com/me
response = requests.get(
    "https://api.example.com/me",
    cookies={"session": "abc123", "theme": "dark"},
)

Using httpx (async + HTTP/2)

httpx is a next-generation Python HTTP client that supports async/await and HTTP/2. Its API is nearly identical to requests, making migration simple. Install with pip install httpx.

import httpx

# Synchronous (drop-in replacement for requests)
response = httpx.get("https://api.example.com/users",
    headers={"Authorization": "Bearer TOKEN"})

# Asynchronous
async with httpx.AsyncClient() as client:
    response = await client.get("https://api.example.com/users",
        headers={"Authorization": "Bearer TOKEN"})
    data = response.json()

# HTTP/2 support
client = httpx.Client(http2=True)
response = client.get("https://api.example.com/users")

5. Converting cURL to Go

Go standard library net/http package provides a complete HTTP client. Go code is more verbose than Python or JavaScript, but gives you full control over the request lifecycle including timeouts, connection pooling, and TLS configuration.

// GET with auth header
// curl -H "Authorization: Bearer TOKEN" https://api.example.com/users
package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "time"
)

func main() {
    client := &http.Client{Timeout: 30 * time.Second}

    req, err := http.NewRequest("GET", "https://api.example.com/users", nil)
    if err != nil {
        panic(err)
    }
    req.Header.Set("Authorization", "Bearer "+os.Getenv("API_TOKEN"))
    req.Header.Set("Accept", "application/json")

    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    fmt.Println(string(body))
}
// POST with JSON body
// curl -X POST -H "Content-Type: application/json" \
//   -d '{"name":"John"}' https://api.example.com/users
payload := strings.NewReader(`{"name":"John","email":"john@example.com"}`)

req, err := http.NewRequest("POST", "https://api.example.com/users", payload)
if err != nil {
    panic(err)
}
req.Header.Set("Content-Type", "application/json")

resp, err := client.Do(req)
if err != nil {
    panic(err)
}
defer resp.Body.Close()
// File upload (multipart/form-data)
// curl -F "file=@photo.jpg" https://api.example.com/upload
var buf bytes.Buffer
writer := multipart.NewWriter(&buf)

part, err := writer.CreateFormFile("file", "photo.jpg")
if err != nil {
    panic(err)
}
file, _ := os.Open("photo.jpg")
io.Copy(part, file)
writer.Close()

req, _ := http.NewRequest("POST", "https://api.example.com/upload", &buf)
req.Header.Set("Content-Type", writer.FormDataContentType())
resp, _ := client.Do(req)
// Basic auth
// curl -u user:password https://api.example.com/data
req, _ := http.NewRequest("GET", "https://api.example.com/data", nil)
req.SetBasicAuth("user", "password")
resp, _ := client.Do(req)

6. Converting cURL to PHP

PHP has a built-in cURL extension (php-curl) that mirrors the command-line tool closely. For modern PHP projects, the Guzzle HTTP client provides a more developer-friendly API. Both approaches are shown below.

// PHP cURL extension - GET with auth
// curl -H "Authorization: Bearer TOKEN" https://api.example.com/users
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/users");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer " . getenv("API_TOKEN"),
    "Accept: application/json"
]);
$response = curl_exec($ch);
$data = json_decode($response, true);
curl_close($ch);
// PHP cURL extension - POST with JSON
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.example.com/users");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "name" => "John",
    "email" => "john@example.com"
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json"
]);
$response = curl_exec($ch);
curl_close($ch);
// Guzzle HTTP client (composer require guzzlehttp/guzzle)
use GuzzleHttp\Client;

$client = new Client(["base_uri" => "https://api.example.com"]);

// GET with Bearer auth
$response = $client->get("/users", [
    "headers" => ["Authorization" => "Bearer " . getenv("API_TOKEN")]
]);
$data = json_decode($response->getBody(), true);

// POST with JSON
$response = $client->post("/users", [
    "json" => ["name" => "John", "email" => "john@example.com"]
]);

// File upload
$response = $client->post("/upload", [
    "multipart" => [
        ["name" => "file", "contents" => fopen("photo.jpg", "r"),
         "filename" => "photo.jpg"],
        ["name" => "description", "contents" => "Profile photo"]
    ]
]);

7. Converting cURL to Ruby

Ruby provides Net::HTTP in the standard library and Faraday as a popular third-party alternative. Net::HTTP is verbose but requires no additional dependencies. Faraday provides middleware support and a cleaner API.

# Ruby Net::HTTP - GET with auth
# curl -H "Authorization: Bearer TOKEN" https://api.example.com/users
require "net/http"
require "json"
require "uri"

uri = URI("https://api.example.com/users")
req = Net::HTTP::Get.new(uri)
req["Authorization"] = "Bearer #{ENV['API_TOKEN']}"
req["Accept"] = "application/json"

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(req)
data = JSON.parse(response.body)
# Ruby Net::HTTP - POST with JSON
uri = URI("https://api.example.com/users")
req = Net::HTTP::Post.new(uri)
req["Content-Type"] = "application/json"
req.body = { name: "John", email: "john@example.com" }.to_json

http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(req)
# Faraday (gem install faraday)
require "faraday"

conn = Faraday.new(url: "https://api.example.com") do |f|
  f.request :json
  f.response :json
end

# GET with auth
response = conn.get("/users") do |req|
  req.headers["Authorization"] = "Bearer #{ENV['API_TOKEN']}"
end

# POST with JSON
response = conn.post("/users", { name: "John", email: "john@example.com" })

8. Converting cURL to Rust

Rust uses the reqwest crate as the de facto HTTP client. It provides both blocking and async APIs, automatic JSON serialization with serde, and robust TLS support. Add to Cargo.toml: reqwest = { version = "0.12", features = ["json"] }.

// Rust reqwest - GET with auth
// curl -H "Authorization: Bearer TOKEN" https://api.example.com/users
use reqwest;
use std::env;

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let token = env::var("API_TOKEN").expect("API_TOKEN not set");

    let client = reqwest::Client::new();
    let response = client
        .get("https://api.example.com/users")
        .header("Authorization", format!("Bearer {}", token))
        .header("Accept", "application/json")
        .send()
        .await?;

    let data: serde_json::Value = response.json().await?;
    println!("{:?}", data);
    Ok(())
}
// Rust reqwest - POST with JSON
use serde_json::json;

let response = client
    .post("https://api.example.com/users")
    .json(&json!({
        "name": "John",
        "email": "john@example.com"
    }))
    .send()
    .await?;
// Rust reqwest - File upload (multipart)
let file_bytes = std::fs::read("photo.jpg")?;
let part = reqwest::multipart::Part::bytes(file_bytes)
    .file_name("photo.jpg")
    .mime_str("image/jpeg")?;

let form = reqwest::multipart::Form::new()
    .part("file", part)
    .text("description", "Profile photo");

let response = client
    .post("https://api.example.com/upload")
    .multipart(form)
    .send()
    .await?;

9. Handling Authentication Patterns

Authentication is one of the most common aspects of cURL-to-code conversion. Here are the three major patterns and how they translate across languages.

Bearer Token (OAuth 2.0, JWT)

Bearer tokens are the most common authentication method for modern APIs. The cURL command uses -H "Authorization: Bearer TOKEN". In every language, this translates to setting the Authorization header with the value "Bearer " followed by the token string. Always load tokens from environment variables or a secure vault.

Basic Authentication

Basic auth sends username:password Base64-encoded in the Authorization header. cURL handles this with -u username:password. Most HTTP client libraries provide a dedicated auth parameter that handles encoding automatically: auth parameter in requests (Python), auth option in axios (JavaScript), SetBasicAuth method in Go, and CURLOPT_USERPWD in PHP cURL.

API Key Authentication

API keys can be sent as a header (X-API-Key: KEY), query parameter (?api_key=KEY), or in the request body. The cURL command varies: -H "X-API-Key: KEY" for header-based, or the key is appended to the URL for query parameter-based. In code, header-based keys are added to the headers object, while query parameter keys are appended to the URL or added to a params object.

10. Multipart/Form-Data and File Uploads

File uploads use the -F flag in cURL, which sends multipart/form-data. This is more complex to convert than simple JSON requests because each language constructs multipart bodies differently.

Key points for multipart conversion: Do not set the Content-Type header manually. The HTTP client must set it automatically to include the multipart boundary string. Mix file fields and text fields freely. The -F flag supports both -F "file=@path" for files and -F "field=value" for text. Multiple files can be uploaded with multiple -F flags.

In JavaScript, use the FormData API and append files and text fields. In Python, use the files parameter for file fields and data parameter for text fields. In Go, use multipart.Writer to construct the body. In PHP, use CURLFile for file fields.

11. Converting Complex cURL with Cookies and Headers

Real-world API calls often involve multiple headers, cookies, and complex request bodies. Here is how to handle these complex scenarios.

When a cURL command has many -H flags, collect all headers into a single object or map in your target language. When -b sends cookies, either add them as a Cookie header or use the language dedicated cookie handling mechanism.

A complex cURL command with multiple headers and cookies:

curl -X PUT \
  -H "Authorization: Bearer TOKEN" \
  -H "Content-Type: application/json" \
  -H "X-Request-ID: req-123" \
  -H "Accept-Language: en-US" \
  -b "session=abc123; csrf=xyz789" \
  -d '{"status":"active","role":"admin"}' \
  https://api.example.com/users/42
# Python equivalent of the complex cURL above
response = requests.put(
    "https://api.example.com/users/42",
    headers={
        "Authorization": "Bearer TOKEN",
        "Content-Type": "application/json",
        "X-Request-ID": "req-123",
        "Accept-Language": "en-US",
    },
    cookies={"session": "abc123", "csrf": "xyz789"},
    json={"status": "active", "role": "admin"},
)
// JavaScript fetch equivalent
const response = await fetch("https://api.example.com/users/42", {
  method: "PUT",
  headers: {
    "Authorization": "Bearer TOKEN",
    "Content-Type": "application/json",
    "X-Request-ID": "req-123",
    "Accept-Language": "en-US",
    "Cookie": "session=abc123; csrf=xyz789"
  },
  body: JSON.stringify({ status: "active", role: "admin" })
});

12. Automating cURL Conversion in CI/CD

In polyglot codebases and microservice architectures, maintaining API client code across multiple languages is a recurring challenge. Automating cURL conversion can streamline this process.

Approach 1: Store canonical cURL commands in a central API specification file (alongside OpenAPI/Swagger docs). Run a conversion script during CI to generate client code for each target language. This ensures all language clients stay in sync.

Approach 2: Use cURL commands as integration test definitions. Write your API tests as cURL commands, then convert them to language-specific test scripts. This gives you a single source of truth for API behavior that is easy to test from the command line.

Approach 3: Generate API client libraries from cURL examples in documentation. Parse API docs for cURL code blocks, convert to target languages, and package as reusable client libraries. This is especially useful for internal APIs where you control the documentation.

#!/bin/bash
# Example: Convert cURL to multiple languages in CI

CURL_CMD='curl -X POST -H "Content-Type: application/json" \
  -d ''''{"query": "test"}'''' https://api.example.com/search'

# Generate code for each target language
for lang in javascript python go php ruby rust; do
  echo "=== $lang ==="
  convert_curl_to_code "$CURL_CMD" --language "$lang" \
    > "clients/$lang/api_client.generated"
done

13. When to Use cURL vs Native HTTP Libraries

While cURL is invaluable for testing and prototyping, there are situations where you should use native HTTP libraries directly instead of converting from cURL.

Use cURL

Use cURL when: Testing API endpoints quickly from the terminal. Sharing reproducible API examples in documentation. Debugging network issues with -v verbose output. Scripting simple one-off HTTP requests in bash. Demonstrating API usage in language-agnostic tutorials.

Use Native Libraries

Use native HTTP libraries when: Building production API clients with retry logic, circuit breakers, and connection pooling. Implementing complex authentication flows like OAuth 2.0 with token refresh. Handling streaming responses or WebSocket upgrades. Managing request middleware, interceptors, and transforms. Working with typed response objects and SDK-generated clients.

The ideal workflow is: prototype with cURL, convert to code using an automated tool, then enhance the generated code with production patterns like error handling, retries, logging, and monitoring.

14. Best Practices for Production cURL-to-Code Conversion

Converting cURL to code is just the first step. Here are essential best practices for production-ready API client code.

See also: JSON Formatter

  1. Never hardcode secrets: Replace -u credentials and -H "Authorization: Bearer ..." tokens with environment variables. Use a secrets manager (AWS Secrets Manager, HashiCorp Vault, Doppler) in production.
  2. Always set timeouts: cURL has --connect-timeout and --max-time. Set equivalent timeouts in your HTTP client to prevent hanging requests. A request without a timeout is a resource leak waiting to happen.
  3. Handle errors properly: Check HTTP status codes (4xx, 5xx) and implement retry logic with exponential backoff for transient failures (429 Too Many Requests, 503 Service Unavailable).
  4. Set Content-Type explicitly: cURL with -d defaults to application/x-www-form-urlencoded. Most APIs expect application/json. Always include the Content-Type header in your converted code.
  5. Use HTTPS in production: Never convert -k (insecure) to production code. Configure proper TLS certificates and certificate verification.
  6. Implement rate limiting: Respect Retry-After headers and implement client-side rate limiting to avoid being throttled or banned by the API.
  7. Log requests for debugging: Add structured logging for request URL, method, status code, and duration. This is the code equivalent of cURL verbose mode.
  8. Use connection pooling: For high-volume API calls, reuse HTTP client instances instead of creating new ones per request. Most libraries support persistent connections.

Frequently Asked Questions

How do I convert a cURL command to JavaScript fetch?

Map cURL flags to fetch options: -X POST becomes method: "POST", each -H becomes an entry 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 using btoa(). Use our free online cURL to Code converter to automate this process instantly.

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 when combined 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 construction in JavaScript, files parameter in Python requests, or multipart.Writer in Go.

How do I handle Basic auth from cURL in Python?

The cURL flag -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"}. For API keys, add them as a header: headers={"X-API-Key": "YOUR_KEY"}.

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 (net/http), PHP (cURL extension and Guzzle), Ruby (Net::HTTP), and Rust (reqwest). Paste your cURL command and select your target language to get production-ready code instantly.

How do I convert a cURL file upload command to code?

cURL file uploads use -F "file=@filename.jpg". In JavaScript, create a FormData object and append the file. In Python, use requests.post(url, files={"file": open("filename.jpg", "rb")}). In Go, use multipart.NewWriter to construct the form body. In PHP, use new CURLFile("filename.jpg"). Each language handles the multipart boundary and Content-Type header automatically.

Why does my converted code return a different response than cURL?

Common causes: Missing Content-Type header (cURL with -d defaults to application/x-www-form-urlencoded, but your API may expect application/json). Missing User-Agent header (some APIs block requests without one). Different redirect behavior (cURL with -L follows redirects, but some libraries do not by default). TLS issues (cURL may use different certificate stores). Always compare headers and body between cURL -v output and your code.

How do I handle cookies when converting cURL to code?

The cURL flag -b sends cookies in the format -b "name=value; name2=value2". In Python requests, use the cookies parameter: requests.get(url, cookies={"name": "value"}). In JavaScript fetch, add a Cookie header: headers: {"Cookie": "name=value"}. In Go, create http.Cookie objects and add them to the request. For complex cookie management, use a cookie jar or session object.

Is it safe to paste cURL commands into online converters?

Be cautious with cURL commands containing real API keys, tokens, or passwords. Our DevToolBox converter processes everything client-side in your browser, so your data never leaves your machine. However, always replace real credentials with placeholders before sharing cURL commands in documentation, bug reports, or online tools that may process server-side.

Conclusion

Converting cURL to code is a fundamental skill for every developer who works with APIs. By understanding how cURL flags map to HTTP client options in JavaScript, Python, Go, PHP, Ruby, and Rust, you can quickly translate any API example into production-ready code. Use our free online cURL to Code converter to automate the conversion, and follow the best practices in this guide to build robust, secure, and maintainable API client code.

Convert cURL commands to any programming language with our free tool.
𝕏 Twitterin LinkedIn
この記事は役に立ちましたか?

最新情報を受け取る

毎週の開発ヒントと新ツール情報。

スパムなし。いつでも解除可能。

Try These Related Tools

🔄cURL to Code Converter{ }JSON FormatterJWTJWT Decoder%20URL Encoder/Decoder

Related Articles

curlコマンドチートシート:API テスト用50+の例

究極のcurlチートシート。GET、POST、ヘッダー、認証、ファイルアップロード、デバッグを網羅。

curlからコードへ:curlコマンドをプログラミング言語に変換

curlコマンドをPython、JavaScript、Go、PHPなどに変換する方法。

API認証:OAuth 2.0 vs JWT vs APIキー

API認証方式を比較:OAuth 2.0、JWT Bearerトークン、APIキー。各方式の使い分け、セキュリティトレードオフ、実装パターン。

REST API ベストプラクティス:2026年完全ガイド

REST API設計のベストプラクティス:命名規則、エラーハンドリング、認証、ページネーション、セキュリティを解説。