cURL to Code Converter · Tutorial
How to send JSON to an API with JavaScript fetch
6 min readbeginnerUpdated
An API’s docs show how to post a message with curl, but you need it in a Node.js script. You will convert the command, check the result for errors and move the token into an environment variable.
What you need
- The cURL to Code Converter
- Node.js 18 or later
Steps
Paste the curl example
Load the example. It uses
--json, a newer curl shortcut that sends a JSON body and sets theContent-TypeandAcceptheaders toapplication/json.Read the fetch code
The converter sets
method: "POST", both JSON headers, the bearer token and a body built withJSON.stringify. Edit the object directly instead of a long string.Check for errors
fetch only throws for network failures, not for 4xx or 5xx responses. Check
response.okand read the error message the API returns.if (!response.ok) { throw new Error(`API error ${response.status}: ${await response.text()}`); } const data = await response.json();Move the token out
Replace
YOUR_TOKENwith a value read fromprocess.env.API_TOKENand run the script withAPI_TOKEN=… node send.mjs, so the token never ends up in Git.
Try it yourself
Opens the cURL to Code Converter with this tutorial's sample loaded.
Common mistakes
- Forgetting JSON.stringify
- Passing an object straight to
bodysends the text “[object Object]”. The converter always wraps it for you; keep it that way when editing. - Calling the API from a web page with a secret token
- Anything in front-end code is visible to visitors. Call the API from your server and let the page talk to your server.
Next steps
Go back to the cURL to Code Converter, or keep going with one of these:
FAQ
What does --json do in curl?
It is short for --data plus Content-Type: application/json and Accept: application/json. It needs curl 7.82 or later.