developerTools

How to Convert cURL Commands to Fetch, Axios, and Python Requests

Translate terminal cURL commands into production-ready JavaScript Fetch, Axios, and Python code. Master GET and POST requests, headers, JSON bodies, authentication, and error handling.

#cURL#Fetch#Axios#Python#API

Quick Answer: How to Translate cURL Commands Converting a terminal curl command into programming code requires mapping command-line flags to their HTTP client library equivalents: - Request URL & Query String: Passed directly to the first argument of fetch(url), axios.get(url), or requests.get(url). - HTTP Method (`-X, --request`): Mapped to method: 'POST' in Fetch, axios.post() or method: 'post', and requests.post() in Python. - Headers (`-H, --header`): Converted into a key-value dictionary in the headers property. - Request Body (`-d, --data, --data-raw`): Passed as body: JSON.stringify(data) in Fetch, data: payload in Axios (which auto-serializes objects), or json=payload in Python Requests. - Authentication (`-u, --user`): Converted to an Authorization: Basic <base64> header, auth: { username, password } in Axios, or auth=('user', 'pass') in Python.

Use the C³ MindLoop cURL to Code Converter to automatically parse flags and generate syntax-highlighted snippets in your browser with zero server uploads.

Step-by-Step Conversion Workflow When translating an API call copied from Chrome DevTools, Postman, or terminal documentation into an application codebase, follow this 4-step workflow:

  1. Extract and Clean the Target URL: Remove shell line continuations (\) and extract query parameters. If parameters contain dynamic values, construct them using URL parameter builders (URLSearchParams in JavaScript or params dict in Python) rather than raw string concatenation.
  2. Normalize Headers and Authentication: Separate generic headers (Content-Type, Accept) from credential headers (Authorization: Bearer <TOKEN>). Store secrets in environment variables instead of hardcoding raw strings.
  3. Format Request Payloads: Determine whether the -d data is raw JSON or URL-encoded form data (application/x-www-form-urlencoded). Multipart file uploads (-F) require a separate implementation using FormData in JavaScript or files= in Python Requests and are not covered by the examples below.
  4. Implement Robust Error and Timeout Handling: Never assume a request succeeds. Implement proper HTTP status checks, catch blocks, and explicit timeout signals to prevent hanging sockets.

cURL Flags to Library Syntax Reference Table

cURL FlagPurposeJavaScript FetchJavaScript AxiosPython Requests
-X GET / POSTHTTP Methodmethod: 'POST'axios.post()requests.post()
-H "Name: Val"HTTP Headerheaders: { 'Name': 'Val' }headers: { 'Name': 'Val' }headers={'Name': 'Val'}
-d '{"a":1}'JSON Payloadbody: JSON.stringify({a: 1})data: { a: 1 }json={'a': 1}
-d "a=1&b=2"Form URL-encodedbody: new URLSearchParams(...)data: new URLSearchParams(...)data={'a': 1, 'b': 2}
-u "usr:pwd"Basic Authheaders: { Authorization: 'Basic ...' }auth: { username, password }auth=('usr', 'pwd')
-m 10Timeout (seconds)signal: AbortSignal.timeout(10000)timeout: 10000timeout=10.0

GET Request Conversion Examples Consider this standard authenticated GET request with query parameters:

bash
curl -X GET "https://api.example.com/v1/users?role=developer&status=active" \
  -H "Accept: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

1. Modern JavaScript (Fetch API) ```javascript // Native Fetch (Browser & Node.js 18+) async function fetchUsers() { const url = new URL('https://api.example.com/v1/users'); url.searchParams.set('role', 'developer'); url.searchParams.set('status', 'active');

const response = await fetch(url.toString(), { method: 'GET', headers: { 'Accept': 'application/json', 'Authorization': Bearer ${process.env.API_TOKEN}, }, signal: AbortSignal.timeout(8000), // 8-second timeout });

// Fetch does NOT reject on 4xx/5xx HTTP errors! if (!response.ok) { throw new Error(HTTP error ${response.status}: ${response.statusText}); }

const data = await response.json(); return data; } ```

2. JavaScript / TypeScript (Axios) ```javascript // Axios Client import axios from 'axios';

async function fetchUsers() { try { const response = await axios.get('https://api.example.com/v1/users', { params: { role: 'developer', status: 'active', }, headers: { 'Accept': 'application/json', 'Authorization': Bearer ${process.env.API_TOKEN}, }, timeout: 8000, });

// Axios automatically parses JSON and rejects non-2xx status codes return response.data; } catch (error) { if (axios.isAxiosError(error)) { console.error(API Error ${error.response?.status}:, error.response?.data); } else { console.error('Network or client error:', error); } throw error; } } ```

3. Python (Requests) ```python # Python Requests import os import requests from requests.exceptions import RequestException

def fetchusers(): url = "https://api.example.com/v1/users" params = { "role": "developer", "status": "active" } headers = { "Accept": "application/json", "Authorization": f"Bearer {os.environ.get('APITOKEN')}" }

try: response = requests.get(url, params=params, headers=headers, timeout=8.0) # Explicitly raise exception for 4xx and 5xx status codes response.raiseforstatus() return response.json() except RequestException as err: print(f"Request failed: {err}") raise ```

POST Request Conversion with JSON Payload Now consider a POST request creating a resource:

bash
curl -X POST https://api.example.com/v1/projects \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  -d '{"name":"C3 MindLoop","isPrivate":true,"tags":["developer","utilities"]}'

1. Modern JavaScript (Fetch API) ``javascript async function createProject(projectData) { const response = await fetch('https://api.example.com/v1/projects', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': Bearer ${process.env.API_TOKEN}`, }, body: JSON.stringify(projectData), signal: AbortSignal.timeout(10000), });

if (!response.ok) { const errorBody = await response.text(); throw new Error(Failed to create project (${response.status}): ${errorBody}); }

return await response.json(); } ```

2. JavaScript / TypeScript (Axios) ```javascript import axios from 'axios';

async function createProject(projectData) { const response = await axios.post( 'https://api.example.com/v1/projects', projectData, // Axios auto-serializes objects to JSON and sets Content-Type { headers: { 'Authorization': Bearer ${process.env.API_TOKEN}, }, timeout: 10000, } ); return response.data; } ```

3. Python (Requests) ```python import os import requests

def createproject(projectdata): url = "https://api.example.com/v1/projects" headers = { "Authorization": f"Bearer {os.environ.get('API_TOKEN')}" }

# Using json= automatically serializes and sets Content-Type: application/json response = requests.post( url, json=projectdata, headers=headers, timeout=10.0 ) response.raisefor_status() return response.json() ```

Critical Differences and Gotchas Between Clients

1. The Fetch ok Gotcha The single most frequent bug in cURL-to-Fetch conversion is assuming fetch() rejects when an API returns HTTP 401, 404, or 500. It does not. Fetch only rejects on network failures (DNS resolution error, TCP reset, or blocked connection). You must check if (!response.ok) manually. In contrast, Axios rejects on any non-2xx status code, and Python Requests requires calling response.raise_for_status().

2. Automatic JSON Serialization - Fetch: Requires manual JSON.stringify(payload) in body and explicit 'Content-Type': 'application/json' header. - Axios: Serializes objects passed to data automatically and sets Content-Type: application/json. - Python: Passing a dictionary to json=payload automatically serializes to JSON and sets the header. Passing a dictionary to data=payload sends application/x-www-form-urlencoded form data instead!

3. Browser CORS vs. Terminal Execution cURL runs directly in your OS terminal with zero Cross-Origin Resource Sharing (CORS) restrictions. However, when you convert that cURL command into browser-based JavaScript (fetch or axios), the browser security sandbox applies: - The remote server must send valid Access-Control-Allow-Origin headers. - Custom headers trigger an automated OPTIONS preflight request. - Certain headers (like User-Agent, Cookie, Host, and Referer) are forbidden request headers in browsers and will be silently stripped or error out. If you need to execute arbitrary API calls that violate browser CORS policies, execute them server-side in Node.js, Python, or Go.

4. The --insecure / -k Flag: Never Translate This cURL's -k (or --insecure) flag skips TLS certificate validation, which is sometimes used when testing against self-signed certificates in local or staging environments. Do not reproduce this behavior in application code. The library equivalents — rejectUnauthorized: false in Node.js, verify=False in Python Requests, or InsecureSkipVerify: true in Go — disable all TLS verification and expose requests to man-in-the-middle attacks if left in production builds. Fix the certificate chain instead of disabling validation.

Automating Conversion with C³ MindLoop Instead of manually rewriting headers, escaping strings, and structuring try-catch blocks every time you copy a cURL command from Chrome DevTools, use the C³ MindLoop cURL to Code Converter.

The converter runs 100% locally in your browser memory: - Tokenizes complex single-quoted and double-quoted flags without leaking API tokens or payloads to third-party servers. - Generates ready-to-run snippets for JavaScript Fetch, Axios, Node.js Fetch, Python Requests, Go net/http, and PHP Guzzle. - Automatically handles -X, -H, -d, and -u credential parsing with zero network transmission.

Companion Developer Tool

cURL to Code Converter

Convert cURL commands to JavaScript Fetch, Axios, Node.js Fetch, Python Requests, Go net/http, and PHP Guzzle — 100% client-side, zero server upload.

Open cURL Converter