cURL to fetch converter

Convert curl POST JSON to fetch

API docs usually show requests as curl commands. To send the same JSON POST from JavaScript, the method, headers and body all need to move into the fetch() options. Paste your command below to get code you can run in a browser or Node.js 18 and newer.

cURL to fetch converter
Style
cURL commandCURL

Press Command or Control plus Enter to run. Tab inserts indentation; press Escape, then Tab, to leave the editor.

Result
Your result will appear here.
Ready4 lines · 162 chars

How each curl option maps to fetch

curlfetch
-X POSTmethod: "POST". With -d, curl uses POST even without -X.
-H "Name: value"An entry in headers.
-d / --data-raw with JSONbody: JSON.stringify({...})
--json '{...}'The body, plus Content-Type and Accept set to application/json.
-u user:passAuthorization: Basic ... with the Base64 of user:pass.
-F field=valueA FormData body. Don't set Content-Type yourself; fetch adds the boundary.

Check the status code

Unlike curl with --fail, fetch() only rejects on network errors. A 400 or 500 response still resolves, so check response.ok before reading the body, as the generated code does.

Keep the token out of the browser

$TOKEN in the command is a shell variable. In the generated code it's a plain string, so replace it with a value from your environment, such as process.env.API_TOKEN on a server. Don't ship secret API keys in browser code, where anyone can read them.

Frequently asked questions

Why does my request work in curl but fail with CORS in the browser?

Browsers enforce CORS and curl doesn't. The API has to allow your site's origin, or you send the request from your own server and call that from the browser.

Why do I get 415 Unsupported Media Type?

The server didn't receive a JSON content type. Keep "Content-Type": "application/json" in the headers when the body is JSON.stringify(...).

Can I use this code in Node.js?

Yes. Node.js 18 and newer have fetch built in, so the code runs as it is, inside an async function or an ES module with top-level await.

From the blog