Thuta Learning
API Tutorial
BasicWeb DevelopmentIntermediate

Common Tools (curl/Postman)

API TutorialLesson 425 min

What you'll walk away with

  • Send GET and POST requests with curl, including headers, a JSON body and query parameters
  • Use -i, -v and -w to see the status line, headers and timing
  • Explain when to use a GUI client such as Postman or Insomnia instead of curl
  • Keep tokens out of saved requests by using environment variables

Explain it simply

Explain it simply

Before you write any code against an API, you want to poke at it by hand, the way a mechanic listens to an engine before opening it. A tool that sends one request and shows you the raw answer is exactly that stethoscope. curl does it from the terminal with one line of text. Postman and Insomnia do it with forms and buttons and keep a history for you.

All of them do the same job as the fetch() call you will write later: build a request, send it, show the response. If a request works in curl but fails in your code, the difference is somewhere in the request, and comparing the two will find it.

Problem → Why → Solution

The problem: you cannot see what you actually sent

You copy an example from an API's documentation into your app and get a 400 Bad Request. The error tells you nothing useful. Is the URL wrong, is a header missing, is the JSON malformed, or is your code reshaping the request in some way? Without a way to see exactly what was sent, you are debugging blind.

A common version of this is a body that looks right in your editor but reaches the server with the wrong Content-Type. By the time the server complains you have no idea which part to check first. The fix is to take your app out of the equation and send the same request from a tool whose every flag you understand.

wrong-content-type.sh
# Illustrative: api.example.com is a placeholder host
curl -X POST https://api.example.com/v1/users -d '{"name":"Alice"}'

# With -d and no Content-Type header, curl labels the body
# application/x-www-form-urlencoded, so a JSON-only API may answer
# 415 Unsupported Media Type or 400 Bad Request.

Why does a tool help?

A tool shows you the request as explicit parts: method, URL, headers, body. When every part is visible you can change one thing at a time and see which change fixes the answer, the same method a doctor uses with a thermometer. A request that works in curl but fails in code proves the server is fine and points you at your own code.

Core concept: curl, GUI clients and DevTools

curl is a command-line program for transferring data with URLs. It ships with macOS and most Linux distributions, and Windows 10 and 11 include it as curl.exe. Its strength is that nothing is hidden: every part of the request is a flag. -X chooses the method, -H adds a header, -d sets the request body, and the URL comes last. Run curl --version to check that it is installed.

By default curl prints only the response body. To see the rest, add -i to print the status line and response headers before the body, or -v for the whole conversation, including the request headers curl sent (lines starting with > are sent, lines starting with < are received). -s silences the progress meter, -o file saves the body to a file, and -w "%{http_code}" prints just the status code. Add --max-time 10 so a hung server cannot block you forever, and -f (--fail) so curl exits with a non-zero code on an HTTP error status, which matters in scripts.

Sending JSON is where beginners stumble. -d sends the string as the body but labels it application/x-www-form-urlencoded unless you add -H "Content-Type: application/json". Quoting is the other trap. On macOS and Linux wrap the JSON in single quotes. In Windows cmd.exe single quotes are not quote characters, so wrap the JSON in double quotes and escape the inner ones as \". In PowerShell 5.1 type curl.exe, because plain curl is an alias for Invoke-WebRequest. The way that works in every shell is to put the JSON in a file and use -d @body.json.

GUI clients such as Postman and Insomnia solve different problems from curl. They save requests in collections, let you define environment variables (a base URL for staging and another for production), show formatted JSON, run a chain of requests and, in Postman, let you write test scripts that check the response automatically. Use curl when you want a command you can paste into a bug report or a script; use a GUI client when you are exploring an unfamiliar API and want history and structure. The browser's DevTools Network tab is a third option for APIs your own website already calls: right-click a request and copy it as cURL.

Whichever tool you choose, never paste a real token into a request you plan to save or share. Use variables: export the secret in your shell and reference it in curl (-H "Authorization: Bearer $API_TOKEN"), or put it in a Postman environment variable and reference it as {{token}}. A collection exported with the secret inside is a leaked secret.

Mental model: a stethoscope for requests
  1. Write the request by hand
  2. Send it with curl or Postman
  3. Read status, headers and body
  4. Change one part and send again

Change one thing at a time, so you know which change fixed the problem.

General pattern: a curl command

bash
curl [options] URL

# -X METHOD            choose the method (GET is the default)
# -H "Name: value"     add a header (repeat it for more headers)
# -d 'body' | -d @file send a request body (implies POST)
# -i | -v              show response headers | show the whole exchange
# -s -o file           quiet mode | save the body to a file
# -w "%{http_code}"    print the status code after the response
# --max-time N -f      give up after N seconds | fail on HTTP errors

Options may come before or after the URL. Repeat -H once per header. Using -d switches the method to POST, so -X POST is optional, but it makes the command easier to read. Always quote the URL, because characters such as & would otherwise be handled by the shell itself.

Example: an echo server that shows exactly what arrived

An echo server answers with a description of the request it received, which makes it the best debugging aid for checking what your tool really sends. This script starts one and sends a fetch request equivalent to a curl command. The server reports the method, the URL (query included), the headers and the body it saw. For the Authorization header it reports only whether one was present, never the value, which is a good habit: never write a secret back out.

echo-debug.mjs
import http from "node:http";

// An echo server: it answers with a description of the request it received.
const server = http.createServer((req, res) => {
  let raw = "";
  req.on("data", (chunk) => (raw += chunk));
  req.on("end", () => {
    const seen = {
      method: req.method,
      url: req.url,
      accept: req.headers["accept"],
      contentType: req.headers["content-type"],
      authorization: req.headers["authorization"] ? "(present)" : "(none)",
      body: raw,
    };
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(seen, null, 2));
  });
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
const base = `http://127.0.0.1:${server.address().port}`;

// The same request as:
//   curl -X POST "$BASE/echo?debug=1" -H "Accept: application/json" \
//        -H "Content-Type: application/json" -d '{"name":"Alice"}'
const res = await fetch(`${base}/echo?debug=1`, {
  method: "POST",
  headers: { Accept: "application/json", "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Alice" }),
});
console.log(res.status);
console.log(await res.text());

server.close();

Code breakdown

  1. Lower-case header namescontentType: req.headers["content-type"],

    Node hands you request header names in lower case, whether the client sent Content-Type or content-type. HTTP header names are case-insensitive.

  2. Never echo secretsauthorization: req.headers["authorization"] ? "(present)" : "(none)",

    This reports whether Authorization exists without echoing its value. Debug output tends to end up in logs, and a token written there can leak.

  3. fetch(url, options)const res = await fetch(`${base}/echo?debug=1`, {

    The second argument to fetch, the options object, plays the role of curl's -X, -H and -d flags. ?debug=1 is the query string inside the URL.

  4. Headersheaders: { Accept: "application/json", "Content-Type": "application/json" },

    Accept states the format you can receive, and Content-Type states the format of the body you are sending. The second key contains a hyphen, which is why it needs quotes.

  5. Body is a stringbody: JSON.stringify({ name: "Alice" }),

    A fetch body must be a string (or binary data); a plain object cannot be sent as is, hence JSON.stringify. It matches curl's -d '...'.

  6. Read as textconsole.log(await res.text());

    res.text() returns the body untouched, so you see exactly what the server sent. While debugging it is often better than res.json(), because it does not fail when the answer is not JSON.

You should see
200
{
  "method": "POST",
  "url": "/echo?debug=1",
  "accept": "application/json",
  "contentType": "application/json",
  "authorization": "(none)",
  "body": "{\"name\":\"Alice\"}"
}

The same request written for curl

Here is the curl command equivalent to the fetch call above. api.example.com is a placeholder host reserved for examples. The -i flag makes curl print the response's status line and headers as well.

post-json.sh
curl -i -X POST "https://api.example.com/v1/users?debug=1" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -d '{"name":"Alice"}'

On the wire, what curl sends is plain text like this (Content-Length counts the 16 characters of the body, and the User-Agent version differs between machines). Remember the order: request line, headers, one blank line, then the body.

raw-request.txt
POST /v1/users?debug=1 HTTP/1.1
Host: api.example.com
User-Agent: curl/8.18.0
Accept: application/json
Content-Type: application/json
Content-Length: 16

{"name":"Alice"}

Quoting differs between shells

The curl examples in this course are written for macOS, Linux and Git Bash. In Windows cmd.exe write the JSON as -d "{\"name\":\"Alice\"}"; with single quotes the quote characters themselves would be sent in the body. In PowerShell 5.1 use curl.exe and write -d '{\"name\":\"Alice\"}'. Environment variables are referenced as %API_TOKEN% in cmd and $env:API_TOKEN in PowerShell. To avoid the whole problem in any shell, put the JSON in a file and use -d @body.json.

Choosing between curl and a GUI client

TaskcurlPostman / Insomnia
Pasting into a bug reportCopy one line of textExport or share the request
Exploring an unfamiliar APITyped by handCollections, history, formatted JSON
Automated checksShell scripts (curl -f)Test scripts and a collection runner
Handling secretsShell environment variablesEnvironment variables in the app

Learn both. Nearly every API's documentation offers curl examples, so you need to be able to read them, and a GUI client shines when a team works together. Product details such as menu names and features change between versions, so check the official guide for the version you use.

In real projects

How these tools are used in real projects

When someone reports a production bug, the best way to reproduce it is often to turn the request from the log into a curl command and resend it. Teams share Postman collections as living documentation, so a newcomer can try the API without typing anything. Browser DevTools show exactly which APIs your own web app is calling. CI pipelines often run a short smoke test with curl right after a deploy, before real traffic is sent to the new version.

Deploy scripts and monitoring use curl constantly too. The command below checks whether a service is healthy and lets a script react to the exit code: -f makes 4xx and 5xx fail, and -sS hides the progress meter but still prints an error message. Here too, api.example.com is an example host.

health-check.sh
# Illustrative health check for a deploy script (placeholder host)
curl -fsS --max-time 5 https://api.example.com/health || echo "service is down"

Common mistakes

Common mistakes

1. Using -d without a Content-Type header

Without a Content-Type, curl -d delivers the body as application/x-www-form-urlencoded. An API that accepts only JSON will refuse it with a 415 or a 400. Your JSON may look perfect, but the server cannot read it under that label. Always add -H "Content-Type: application/json".

2. Leaving the URL unquoted

In bash, typing curl https://api.example.com/v1/items?page=1&limit=5 makes the shell read & as "run the command in the background", so limit=5 never reaches curl. Wrap the whole URL in double quotes. In Windows cmd, single quotes do not work, so use double quotes only.

3. Typing a real token straight into the command

Typing curl -H "Authorization: Bearer sk-..." puts the token into your shell history file, and it can slip into a screen share or a bug report. Store the token in an environment variable and reference it as $API_TOKEN, and use an environment variable in Postman as well.

Best practices

Best practices

  • Add -i (or -v) whenever you debug; without the status and headers you are missing half the picture.
  • Use --max-time and -f in scripts, so a failing server cannot hang or silently mislead them.
  • Keep long JSON bodies in a file and send them with -d @file; it avoids quoting trouble and can go into version control.
  • Save requests that work in a collection or a script file, so you can replay them next time.

Mini challenge

Mini challenge: a function that writes the curl command

Write a toCurl() function that takes a { method, url, headers, body } object and returns one curl command string that works in a macOS or Linux shell.

  • Leave out -X when the method is GET (the default); otherwise add -X METHOD
  • Wrap the URL and every other value in single quotes
  • Add one -H 'Name: value' per header
  • When a body exists, add -d '<JSON.stringify(body)>' and escape any single quote inside a value as '\''
to-curl.mjs
// A value wrapped in single quotes for a POSIX shell
function quote(text) {
  // TODO: wrap in ' ... ' and turn every ' inside into '\''
}

function toCurl({ method = "GET", url, headers = {}, body }) {
  // TODO: start with ["curl"]
  // TODO: add -X METHOD unless the method is GET
  // TODO: add the quoted URL
  // TODO: add -H for every header
  // TODO: add -d with the JSON body when there is one
  // TODO: join the parts with spaces
}

// TODO: print toCurl for a plain GET and for a POST with headers and a body

Expected: The output should be (the second command is a single line): curl 'https://api.example.com/v1/health' curl -X POST 'https://api.example.com/v1/users' -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"name":"Alice","nickname":"Ma'\''am"}'

Show hint

To escape a single quote use String(text).replaceAll("'", "'\\''"): in a shell that closes the quote, adds \' and reopens it. Push the parts into an array and call join(" ") at the end.

Show solution
to-curl.mjs
// A value wrapped in single quotes for a POSIX shell
function quote(text) {
  return "'" + String(text).replaceAll("'", "'\\''") + "'";
}

function toCurl({ method = "GET", url, headers = {}, body }) {
  const parts = ["curl"];
  if (method !== "GET") parts.push("-X", method);
  parts.push(quote(url));
  for (const [name, value] of Object.entries(headers)) {
    parts.push("-H", quote(`${name}: ${value}`));
  }
  if (body !== undefined) parts.push("-d", quote(JSON.stringify(body)));
  return parts.join(" ");
}

console.log(toCurl({ url: "https://api.example.com/v1/health" }));
console.log(
  toCurl({
    method: "POST",
    url: "https://api.example.com/v1/users",
    headers: { "Content-Type": "application/json", Accept: "application/json" },
    body: { name: "Alice", nickname: "Ma'am" },
  })
);

Quick quiz 1 / 3

You run curl -X POST https://api.example.com/v1/users -d '{"name":"Alice"}' and the API answers 415 Unsupported Media Type. What is the most likely cause?

Quick quiz 2 / 3

Which flag shows the whole exchange, including the request headers curl sent?

Quick quiz 3 / 3

How should an API token be handled in a Postman collection you will share with a team?

What to remember

  • curl and GUI clients make a request visible; if it works there but not in your code, the problem is in your request.
  • The key curl flags are -X, -H, -d, -i, -v, -s, -o, -w, --max-time and -f, and JSON needs Content-Type: application/json.
  • Quoting differs by shell: double quotes with \" in cmd, curl.exe in PowerShell 5.1, or avoid it all with -d @body.json.
  • Reference real tokens through environment variables; never put them in commands, collections or URLs.

RFC 9110 — HTTP Semantics — IETF

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Common Tools (curl/Postman) | Thuta Learning