Curl-zu-Fetch-Konverter

Konvertieren Sie curl-Befehle zu JavaScript fetch() und umgekehrt

Converting Between curl and the Fetch API

API documentation overwhelmingly uses curl examples to demonstrate HTTP endpoints. When building frontend applications or Node.js services, developers need to translate those curl commands into JavaScript's fetch() API calls — and sometimes the reverse, converting fetch code back to curl for debugging or sharing with teammates who prefer terminal workflows. This bidirectional conversion bridges the gap between the command-line HTTP paradigm and the programmatic fetch interface, enabling faster development cycles and reducing manual translation errors.

Unlike a curl command builder that constructs commands from form inputs, this converter operates on existing code: paste a curl command and get working fetch code, or paste fetch code and get a curl command. The focus is on accurate mapping between two fundamentally different interfaces for making HTTP requests — one designed for terminal usage with flags and arguments, the other designed for JavaScript applications with objects and promises.

How curl Flags Map to Fetch Options

curl uses single-character and long-form flags to configure HTTP requests. Each flag has a direct equivalent in the fetch API's RequestInit options object. Understanding this mapping is the foundation of accurate conversion between the two formats.

The -X (or --request) flag maps to the method property. When omitted in curl, the method defaults to GET unless a body is provided (which triggers POST). The fetch API follows the same convention: omitting method defaults to GET. The -H (or --header) flag maps directly to the headers object. In curl, each header requires a separate -H flag, while fetch accepts all headers as key-value pairs in a single object or Headers instance.

Body data uses -d (or --data) in curl, mapping to the body property in fetch. An important difference: curl's -d automatically sets the Content-Type to application/x-www-form-urlencoded if no Content-Type header is specified, while fetch does not set any default Content-Type for string bodies. This subtle difference causes bugs when developers convert mechanically without accounting for implicit behaviors.

Authentication flags like -u username:password (basic auth) translate to an Authorization header with the Base64-encoded credentials. The -L (follow redirects) flag maps to fetch's redirect: 'follow' option, which is the default behavior in fetch, making -L unnecessary to translate explicitly.

Response Handling: Streams vs Exit Codes

The most significant architectural difference between curl and fetch lies in how they handle responses. curl writes response bodies directly to stdout and communicates success or failure through exit codes (0 for success, non-zero for errors). Developers pipe output to files, other commands, or parse it with tools like jq.

The fetch API returns a Response object wrapped in a Promise. The response body is a ReadableStream that must be consumed explicitly using methods like .json(), .text(), .blob(), or .arrayBuffer(). Critically, fetch does not reject the promise on HTTP error status codes (4xx, 5xx) — it only rejects on network failures. This means a curl command that fails with HTTP 404 exits with code 0 (because the HTTP request succeeded), and similarly, fetch resolves its promise regardless of the status code. Proper error handling in fetch requires checking response.ok or response.status explicitly.

When converting from curl to fetch, the generated code should include response status checking that mirrors what developers expect. When converting from fetch to curl, verbose mode (-v) can be suggested to expose response headers and status codes that would otherwise be invisible in curl's default output mode.

Body Format Conversion Patterns

curl supports multiple body formats through different flags: -d for URL-encoded form data, --data-raw for literal strings without processing, --data-binary for binary data, and -F for multipart form uploads. Each requires a different approach in fetch.

Form-encoded data (-d "key=value&other=data") translates to a string body with an explicit Content-Type: application/x-www-form-urlencoded header, or more idiomatically, a URLSearchParams object as the body (which sets the Content-Type automatically). JSON payloads (-d '{"key":"value"}' with -H 'Content-Type: application/json') map to JSON.stringify() with the appropriate header. Multipart uploads (-F "file=@photo.jpg") become FormData objects in fetch, which automatically set the correct multipart boundary in the Content-Type header.

The reverse direction — fetch to curl — requires detecting which body type is being used. A FormData body maps to -F flags, URLSearchParams maps to -d, and raw strings map to --data-raw. JSON bodies detected by JSON.stringify() calls map to -d with the appropriate Content-Type header.

Practical Developer Scenarios

The most common conversion scenario is translating API documentation examples into application code. REST API providers like Stripe, GitHub, Twilio, and AWS publish curl examples in their documentation. Frontend developers need these as fetch calls within React components, Vue composables, or standalone utility functions. The converter handles the translation including proper header formatting, body serialization, and authentication credential placement.

The reverse scenario — fetch to curl — serves debugging workflows. When a fetch request fails in production, developers extract the request parameters and convert them to curl for testing in the terminal, where they have direct control over TLS certificates, proxy settings, DNS resolution, and verbose output. This is especially useful when diagnosing CORS issues, since curl bypasses browser security policies entirely, helping isolate whether a problem is server-side or browser-enforced.

Another scenario involves CI/CD pipelines and scripts. Developers may write HTTP interactions in fetch for their application, then need equivalent curl commands for shell scripts, Dockerfiles, health checks, or Kubernetes readiness probes where a JavaScript runtime is unavailable.

Code Examples

Converting a curl POST request to fetch

// Original curl command:
// curl -X POST 'https://api.example.com/users' \
//   -H 'Content-Type: application/json' \
//   -H 'Authorization: Bearer token123' \
//   -d '{"name":"Alice","email":"alice@example.com"}'

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

if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}

const data = await response.json();
console.log(data);

Output:

// The fetch call produces the same HTTP request as the curl command:
// POST /users HTTP/1.1
// Host: api.example.com
// Content-Type: application/json
// Authorization: Bearer token123
//
// {"name":"Alice","email":"alice@example.com"}

Converting fetch code back to curl

# Given this fetch code:
# fetch('https://api.example.com/search', {
#   method: 'GET',
#   headers: {
#     'Accept': 'application/json',
#     'X-API-Key': 'sk_live_abc123'
#   }
# })

# Equivalent curl command:
curl 'https://api.example.com/search' \
  -H 'Accept: application/json' \
  -H 'X-API-Key: sk_live_abc123'

Standards & Specifications

  • Fetch Standard (WHATWG) — The living standard defining the Fetch API, Request/Response interfaces, and CORS
  • curl man page — Official curl documentation covering all flags and options used in HTTP transfers
  • MDN Fetch API — Practical guide to using the Fetch API including RequestInit options and error handling

Häufig Gestellte Fragen

Why would I need to convert curl to fetch?

API documentation often provides curl examples because curl is universal and works in any terminal. However, when implementing APIs in web applications, you need JavaScript fetch() code. This tool saves time by automatically converting curl commands from docs into ready-to-use fetch() code, preserving all headers, authentication, and request bodies.

What's the difference between JavaScript and TypeScript output?

JavaScript output uses promise chains (.then/.catch) and standard fetch syntax suitable for any JavaScript environment. TypeScript output wraps the code in an async function, uses await syntax for cleaner code, and includes 'as const' type annotations. Choose JavaScript for broader compatibility or TypeScript for modern codebases with async/await support.

Can I convert fetch code back to curl?

Yes! Switch to the 'Fetch → Curl' tab and paste your fetch() code. The tool will extract the method, URL, headers, and body, then generate an equivalent curl command. This is useful when you have working application code and need to test the same request in your terminal or share it with teammates.

Does the converter handle authentication headers?

Yes, the converter preserves all authentication headers including Bearer tokens, Basic auth, and API keys. When converting curl to fetch, authentication headers are included in the headers object. When converting fetch to curl, they're added as -H flags. Your credentials remain private as all conversion happens in your browser.

What happens to the request body during conversion?

Request bodies are preserved during conversion. In curl commands, bodies are specified with the -d flag. In fetch() code, they're included in the body property of the options object. The converter handles JSON bodies, form data, and plain text, maintaining proper escaping and formatting.

Should I include error handling in the generated code?

For production code, yes. Error handling checks response.ok and catches network failures, preventing silent errors. For quick prototyping or testing, you can disable it for simpler code. TypeScript output with error handling includes try/catch blocks and proper error propagation, while JavaScript uses .catch() in the promise chain.

Is my data sent to a server during conversion?

No, all conversion happens entirely in your browser. Your curl commands, fetch code, URLs, headers, authentication tokens, and request bodies never leave your device. This ensures complete privacy when working with sensitive API credentials or production endpoints.