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

Steps

  1. Paste the curl example

    Load the example. It uses --json, a newer curl shortcut that sends a JSON body and sets the Content-Type and Accept headers to application/json.

  2. Read the fetch code

    The converter sets method: "POST", both JSON headers, the bearer token and a body built with JSON.stringify. Edit the object directly instead of a long string.

  3. Check for errors

    fetch only throws for network failures, not for 4xx or 5xx responses. Check response.ok and 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();
  4. Move the token out

    Replace YOUR_TOKEN with a value read from process.env.API_TOKEN and run the script with API_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.

Try it now

Common mistakes

Forgetting JSON.stringify
Passing an object straight to body sends 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.