Introduction

cURL is great for testing APIs, but in JavaScript applications, you’ll want to use the modern fetch() API. This guide shows how to convert cURL commands to fetch() calls.

Basic Conversion

Simple GET Request

cURL:

curl https://api.example.com/users

fetch():

fetch("https://api.example.com/users")
  .then((response) => response.json())
  .then((data) => console.log(data));

With Headers

cURL:

curl -H "Content-Type: application/json" \
     -H "Authorization: Bearer token123" \
     https://api.example.com/users

fetch():

fetch("https://api.example.com/users", {
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer token123",
  },
})
  .then((response) => response.json())
  .then((data) => console.log(data));

POST Requests

JSON Body

cURL:

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

fetch():

fetch("https://api.example.com/users", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    name: "Alice",
    email: "alice@example.com",
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Form Data

cURL:

curl -X POST https://api.example.com/upload \
     -F "file=@image.jpg" \
     -F "name=My Image"

fetch():

const formData = new FormData();
formData.append("file", fileInput.files[0]);
formData.append("name", "My Image");

fetch("https://api.example.com/upload", {
  method: "POST",
  body: formData,
});

Common Patterns

Error Handling

cURL: (shows HTTP errors in output)

fetch():

fetch("https://api.example.com/users")
  .then((response) => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json();
  })
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));

Query Parameters

cURL:

curl "https://api.example.com/search?q=test&limit=10"

fetch():

const params = new URLSearchParams({
  q: "test",
  limit: "10",
});

fetch(`https://api.example.com/search?${params}`);

Tools

Use our tools:

Conclusion

Converting cURL to fetch():

Key conversions:

  • -X POSTmethod: 'POST'
  • -Hheaders object
  • -dbody (JSON.stringify for JSON)
  • Query params → URLSearchParams

Benefits:

  • Native browser API
  • Promise-based
  • Type-safe (with TypeScript)
  • Modern async/await support

Next Steps