curl to Code Converter — Convert Any curl Command to JavaScript, Python, Go, and More

curl is the universal language of HTTP requests. But running curl in production code requires translation to your programming language. This guide shows how to convert any curl command to JavaScript fetch, axios, Python requests, Go net/http, PHP cURL, and more — with examples, a reference for every common curl flag, and tools that do it automatically.

7+

languages covered in this guide

Every flag

curl -H, -d, -X, -u, -k, -b all covered

Auto-convert

tools to automate the conversion

Copy-paste

ready code examples for every pattern

1

curl to JavaScript — fetch() and axios

Itemcurl CommandJavaScript fetch()
GETcurl https://api.example.com/usersfetch('https://api.example.com/users')
POST JSONcurl -X POST -H 'Content-Type: application/json' -d '{"name":"Alice"}' URLfetch(url, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({name:'Alice'}) })
Auth headercurl -H 'Authorization: Bearer TOKEN' URLfetch(url, { headers: {'Authorization': 'Bearer TOKEN'} })
Basic authcurl -u user:pass URLfetch(url, { headers: {'Authorization': 'Basic ' + btoa('user:pass')} })
Form datacurl -F "key=val" URLfetch(url, { method:"POST", body: new FormData() })
Cookiecurl -b "session=abc123" URLfetch(url, { headers: {'Cookie': 'session=abc123'}, credentials: 'include' })
javascriptComplete curl → fetch Conversion
// curl -X POST https://api.example.com/users \
//   -H "Authorization: Bearer mytoken" \
//   -H "Content-Type: application/json" \
//   -d '{"name":"Alice","email":"alice@example.com"}'

// → JavaScript fetch():
const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer mytoken',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' }),
});

if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();

// → axios (cleaner, auto-serializes JSON):
import axios from 'axios';

const { data } = await axios.post('https://api.example.com/users',
  { name: 'Alice', email: 'alice@example.com' },    // body (auto JSON.stringify)
  { headers: { 'Authorization': 'Bearer mytoken' } } // config
);

// → Node.js with node-fetch or built-in fetch (Node 18+):
// Same as browser fetch — no import needed in Node 18+
2

curl to Python requests

pythoncurl → Python requests
# curl -X POST https://api.example.com/users \
#   -H "Authorization: Bearer mytoken" \
#   -H "Content-Type: application/json" \
#   -d '{"name":"Alice","email":"alice@example.com"}'

import requests

response = requests.post(
    'https://api.example.com/users',
    json={'name': 'Alice', 'email': 'alice@example.com'},  # json= auto-sets Content-Type
    headers={'Authorization': 'Bearer mytoken'}
)
response.raise_for_status()  # raises for 4xx/5xx
data = response.json()

# curl -u user:pass URL  →  Basic auth:
response = requests.get(url, auth=('user', 'pass'))

# curl -k URL  →  Skip SSL:
response = requests.get(url, verify=False)

# curl -F "file=@photo.jpg" URL  →  File upload:
with open('photo.jpg', 'rb') as f:
    response = requests.post(url, files={'file': f})

# curl -b "session=abc" URL  →  Cookies:
response = requests.get(url, cookies={'session': 'abc'})

# curl --max-time 30 URL  →  Timeout:
response = requests.get(url, timeout=30)  # total timeout
response = requests.get(url, timeout=(5, 30))  # (connect, read)
3

curl to Go (net/http)

gocurl → Go net/http
// curl -X POST https://api.example.com/users \
//   -H "Authorization: Bearer mytoken" \
//   -H "Content-Type: application/json" \
//   -d '{"name":"Alice"}'

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

func main() {
    // Build request body
    body, _ := json.Marshal(map[string]string{"name": "Alice"})

    // Create request
    req, _ := http.NewRequest("POST", "https://api.example.com/users", bytes.NewReader(body))
    req.Header.Set("Authorization", "Bearer mytoken")
    req.Header.Set("Content-Type", "application/json")

    // Client with timeout (curl --max-time 30)
    client := &http.Client{Timeout: 30 * time.Second}

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

    if resp.StatusCode >= 400 {
        panic(fmt.Sprintf("HTTP error: %d", resp.StatusCode))
    }

    respBody, _ := io.ReadAll(resp.Body)
    fmt.Println(string(respBody))
}
4

curl to PHP and Ruby

phpcurl → PHP (Guzzle and native cURL)
<?php
// Using Guzzle (recommended):
// composer require guzzlehttp/guzzle

use GuzzleHttpClient;

$client = new Client();
$response = $client->post('https://api.example.com/users', [
    'headers' => ['Authorization' => 'Bearer mytoken'],
    'json'    => ['name' => 'Alice', 'email' => 'alice@example.com'],
]);
$data = json_decode($response->getBody(), true);

// Using native PHP cURL:
$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']),
    CURLOPT_HTTPHEADER    => [
        'Authorization: Bearer mytoken',
        'Content-Type: application/json',
    ],
    CURLOPT_TIMEOUT       => 30,
    // curl -k: CURLOPT_SSL_VERIFYPEER => false,
]);
$result = curl_exec($ch);
curl_close($ch);
5

curl Flag Reference

Itemcurl FlagWhat It Does
-X POST / -X PUTHTTP methodSpecify method (default is GET for no body, POST with -d)
-H "Key: Val"Add request headerAuthorization, Content-Type, X-API-Key, any custom header
-d "data"Request bodySends data as POST body. Implies -X POST if -X not set.
--data-rawRaw body stringLike -d but no @ file reading or special character processing
--data-urlencodeURL-encoded bodyURL-encodes the value before sending as form data
-u user:passBasic authBase64-encodes to Authorization: Basic header
-b "key=val"CookieSends Cookie header with specified values
-c fileCookie jar writeSaves received cookies to file for reuse
-F "key=val"Multipart formSends multipart/form-data. Use -F "file=@path" for file upload.
-k / --insecureSkip SSL verifyAccepts any certificate (dev only — never in production)
--connect-timeout NConnection timeoutSeconds before TCP connection attempt fails
--max-time NTotal timeoutMax seconds for the entire request including transfer
-LFollow redirectsFollows 301/302 redirects automatically
-o fileSave to fileWrite response body to specified file
-vVerbosePrint request/response headers, timing, and connection info
--proxy http://p:8080HTTP proxyRoute request through specified proxy
6

Auto-Conversion Tools

curlconverter.com

Paste any curl command, get instant code in 20+ languages including Python, JavaScript, Go, PHP, Java, Ruby, Rust, Swift, Kotlin, and more. Open source. Handles most edge cases automatically.

Bruno / Insomnia Import

Both API clients let you paste a curl command to create a saved request collection. Right-click in Insomnia → Paste Curl. In Bruno: drag and drop or paste. Great for turning one-off curl commands into saved API tests.

Chrome DevTools → Copy as fetch

Right-click any request in Network tab → Copy → "Copy as fetch" or "Copy as Node.js fetch". Generates browser-accurate code with all actual headers and cookies sent. The most reliable method.

Claude / ChatGPT

Paste your curl command with "Convert this to Python requests" (or any language). AI handles unusual flags, edge cases, and file uploads that automated converters sometimes miss. Also explains what each flag does.

Get curl from Chrome — then convert

The fastest workflow: Open Chrome DevTools → Network tab → find the request you want to replicate → right-click → Copy → Copy as cURL (bash). This gives you the exact curl command with all real headers and cookies. Then paste into curlconverter.com or your AI of choice for instant production-ready code.
1

Start with curl for discovery

Use curl -v to explore an API endpoint. It shows exactly what headers the server expects and returns, what auth method is needed, and the response format. Much faster to iterate than writing code.

2

Capture from browser if available

If the API works in a browser, right-click the request in DevTools → Copy as cURL. You get the exact working request including all headers and cookies that make it work.

3

Convert automatically

Paste into curlconverter.com or your AI tool of choice. Review the generated code — especially auth headers, body encoding (json vs form data), and timeout settings.

4

Add error handling

The converter gives you happy-path code. Add: response.raise_for_status() in Python, if (!response.ok) throw in JS. Wrap in try/catch for network errors. Set timeout on all calls.

5

Test against same endpoint

Run the original curl and your converted code against the same endpoint and compare responses. If they differ, the difference is in a header, body encoding, or redirect handling.

Frequently Asked Questions

Related API Tools Guides

Continue with closely related troubleshooting guides and developer workflows.