Skip to main content

APIs · Beginner · 20 min

How to Test and Debug an API with curl

By Padding · Updated 15 Nov 2026
curl 8 · Ubuntu 26.04.1 LTS

You will write a small practice API, then call it with curl 8 to read responses and headers, send JSON, send an authorization header without putting the secret on the command line, follow redirects, measure timing, set timeouts and retries, and read curl's verbose output when a request goes wrong.

On this page

curl sends an HTTP request from the terminal and shows you what came back. When an API misbehaves, it is the fastest way to find out whether the fault is in the server or in your code, because it removes your code from the picture. You see the status, the headers and the body, exactly as the server sent them.

To keep every example reproducible, and to avoid sending requests to someone else's server, you first write a small practice API with Python's standard library. It listens on 127.0.0.1:8000, so nothing outside your machine can reach it. It has routes that return JSON, require a token, redirect, respond slowly and fail on purpose. Every curl command below runs against it. Ubuntu 26.04 ships curl 8.18, and the options used here exist in every curl 8 release.

Step 1 · Install curl and Python

Install both. Ubuntu server images often have curl already, and apt leaves it alone then. jq is optional here: it formats JSON, and the jq tutorial covers it:

Bash
sudo apt update
sudo apt install -y curl python3 jq
curl --version | sed -n 1p

The first line of curl --version starts with curl 8..

Step 2 · Write the practice API

Create a working folder and save the server in it. It keeps a list of items in memory. The code is a toy, with no real security, so run it only on your own computer:

Bash
mkdir -p ~/curl-demo
cd ~/curl-demo
cat > server.py <<'PY'
import json
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlparse

ITEMS = [
    {"id": 1, "title": "Read the manual", "done": True},
    {"id": 2, "title": "Test the API", "done": False},
    {"id": 3, "title": "Write it down", "done": False},
]
TOKEN = "demo-token"
state = {"flaky_calls": 0}


class Handler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def reply(self, status, payload=None, headers=None):
        body = b"" if payload is None else json.dumps(payload).encode() + b"\n"
        self.send_response(status)
        if payload is not None:
            self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        for name, value in (headers or {}).items():
            self.send_header(name, value)
        self.end_headers()
        if self.command != "HEAD":
            self.wfile.write(body)

    def read_json(self):
        length = int(self.headers.get("Content-Length", 0))
        try:
            data = json.loads(self.rfile.read(length))
        except ValueError:
            self.reply(400, {"error": "body is not valid JSON"})
            return None
        if not isinstance(data, dict):
            self.reply(400, {"error": "body must be a JSON object"})
            return None
        return data

    def find(self, path):
        try:
            wanted = int(path.rsplit("/", 1)[1])
        except ValueError:
            return None
        return next((i for i in ITEMS if i["id"] == wanted), None)

    def route(self):
        url = urlparse(self.path)
        query = parse_qs(url.query)
        if url.path == "/api/items" and self.command in ("GET", "HEAD"):
            items = ITEMS
            if "q" in query:
                items = [i for i in items if query["q"][0].lower() in i["title"].lower()]
            if "limit" in query:
                items = items[: int(query["limit"][0])]
            return self.reply(200, items)
        if url.path == "/api/items" and self.command == "POST":
            data = self.read_json()
            if data is None:
                return
            title = data.get("title")
            if not isinstance(title, str) or not title.strip():
                return self.reply(422, {"error": "title is required"})
            item = {"id": max(i["id"] for i in ITEMS) + 1, "title": title.strip(), "done": False}
            ITEMS.append(item)
            return self.reply(201, item, {"Location": f"/api/items/{item['id']}"})
        if url.path.startswith("/api/items/"):
            item = self.find(url.path)
            if item is None:
                return self.reply(404, {"error": "no such item"})
            if self.command in ("GET", "HEAD"):
                return self.reply(200, item)
            if self.command == "DELETE":
                ITEMS.remove(item)
                return self.reply(204)
            if self.command == "PUT":
                data = self.read_json()
                if data is None:
                    return
                item["title"] = str(data.get("title", item["title"]))
                item["done"] = bool(data.get("done", item["done"]))
                return self.reply(200, item)
            return self.reply(405, {"error": "method not allowed"}, {"Allow": "GET, HEAD, PUT, DELETE"})
        if url.path == "/api/private":
            if self.headers.get("Authorization") != f"Bearer {TOKEN}":
                return self.reply(401, {"error": "missing or wrong token"}, {"WWW-Authenticate": "Bearer"})
            return self.reply(200, {"secret": "the cake is real"})
        if url.path == "/old-items":
            return self.reply(301, None, {"Location": "/api/items"})
        if url.path == "/api/slow":
            time.sleep(float(query.get("delay", ["3"])[0]))
            return self.reply(200, {"waited": True})
        if url.path == "/api/flaky":
            state["flaky_calls"] += 1
            if state["flaky_calls"] % 3 != 0:
                return self.reply(503, {"error": "try again"}, {"Retry-After": "1"})
            return self.reply(200, {"ok": True})
        return self.reply(404, {"error": "not found"})

    do_GET = do_HEAD = do_POST = do_PUT = do_PATCH = do_DELETE = route

    def log_message(self, format, *args):
        pass


ThreadingHTTPServer(("127.0.0.1", 8000), Handler).serve_forever()
PY

Start it in a second terminal, in the same folder, and leave it running. Stop it with Ctrl+C when you finish:

Bash
cd ~/curl-demo
python3 server.py

The server prints nothing. Run the rest in your first terminal.

Step 3 · Make your first request

With no options, curl sends a GET and prints the response body:

Bash
curl http://127.0.0.1:8000/api/items/1

The output is {"id": 1, "title": "Read the manual", "done": true} on one line. Pipe long responses through jq to make them readable:

Bash
curl -s http://127.0.0.1:8000/api/items | jq .

-s (silent) hides the progress meter that curl shows when its output is not going to a terminal. Without it, the meter is mixed into your pipe's stderr. -S (--show-error) brings error messages back while keeping -s, so -sS is the pair to use in scripts.

Check it worked

Bash
curl -sS http://127.0.0.1:8000/api/items | jq length

The output is 3.

Step 4 · Read the status and the headers

The body is only half of a response. -i includes the status line and headers before the body:

Bash
curl -si http://127.0.0.1:8000/api/items/2

The first line is HTTP/1.1 200 OK, followed by headers such as Content-Type: application/json, Content-Length and Date, a blank line, and then the body. -I sends a HEAD request instead, which asks for the headers only:

Bash
curl -sI http://127.0.0.1:8000/api/items/2

For scripts, -w (write-out) prints chosen details after the transfer. -o /dev/null throws the body away, so you get only the status code:

Bash
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/items/2
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/items/99

The outputs are 200 and 404. A 404 is a normal response, and curl prints its body and exits with status 0, as it does for every HTTP status. Make curl treat HTTP errors as failures with --fail-with-body, which exits with status 22 on a status of 400 or more, and still prints the error body. It exists in curl 7.76 and later:

Bash
curl -sS --fail-with-body http://127.0.0.1:8000/api/items/99 || echo "curl failed with status $?"

You see {"error": "no such item"}, curl's own curl: (22) The requested URL returned error: 404 on stderr, and then curl failed with status 22. Use --fail-with-body rather than -f when the error body helps you. Plain -f hides it.

Check it worked

Bash
curl -s -o /dev/null -w 'status=%{http_code} type=%{content_type}\n' http://127.0.0.1:8000/api/items

The output is status=200 type=application/json.

Step 5 · Send query parameters

Add parameters to the address after a ?. The quotes matter, because the shell treats & and ? specially:

Bash
curl -sS 'http://127.0.0.1:8000/api/items?limit=2' | jq 'map(.id)'

For values with spaces or special characters, let curl encode them. -G makes curl send the --data-urlencode pairs as a query string on a GET:

Bash
curl -sS -G http://127.0.0.1:8000/api/items --data-urlencode 'q=test the' | jq 'map(.title)'

The output is an array with Test the API. Without -G, --data-urlencode would send a POST with a form body.

Step 6 · Send JSON

--json (curl 7.82 and later) sends the data with a POST, sets Content-Type: application/json and Accept: application/json, and sends the data as given. Wrap the JSON in single quotes:

Bash
curl -si --json '{"title": "Deploy it"}' http://127.0.0.1:8000/api/items

The response starts with HTTP/1.1 201 Created. It has a Location: /api/items/4 header that says where the new item lives, and the new item in the body. Bad input should produce a clear error, not a crash. Try three bad requests:

Bash
curl -s -o /dev/null -w '%{http_code}\n' --json '{"title": ""}' http://127.0.0.1:8000/api/items
curl -s -o /dev/null -w '%{http_code}\n' --json '{"wrong": 1}' http://127.0.0.1:8000/api/items
curl -s -w '%{http_code}\n' --json '{not json' http://127.0.0.1:8000/api/items

The first two print 422, meaning the JSON is valid but the content is not acceptable. The third prints {"error": "body is not valid JSON"} and then 400. A good API tells the caller what was wrong, without a stack trace or any internal detail.

Long bodies are easier to keep in a file. Put @ in front of the file name to read the body from it:

Bash
cat > item.json <<'JSON'
{"title": "Ship it"}
JSON
curl -sS --json @item.json http://127.0.0.1:8000/api/items | jq .

--json is shorthand. Under the hood it is -X POST -H 'Content-Type: application/json' -H 'Accept: application/json' --data-binary. -d on its own sends Content-Type: application/x-www-form-urlencoded, and many servers will not parse JSON sent that way.

Check it worked

Bash
curl -sS http://127.0.0.1:8000/api/items | jq 'map(.title)'

The list now includes Deploy it and Ship it.

Step 7 · Use other methods

Choose a method with -X. PUT replaces fields, and DELETE removes. Do not add -X to GET or POST requests: curl chooses them for you, and forcing -X POST on a redirect or with -I causes odd behaviour.

Bash
curl -sS -X PUT --json '{"done": true}' http://127.0.0.1:8000/api/items/2 | jq .
curl -si -X DELETE http://127.0.0.1:8000/api/items/4
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8000/api/items/4

The PUT shows item 2 with "done": true. The DELETE answers HTTP/1.1 204 No Content with no body, and a request for item 4 afterwards gives 404. Calling a method the route does not support returns 405 with an Allow header that lists the ones it does. -D - prints the response headers to the terminal, and -o /dev/null drops the body:

Bash
curl -s -o /dev/null -D - -X PATCH http://127.0.0.1:8000/api/items/2

Step 8 · Send an authorization header without leaking the secret

Many APIs expect a token in the Authorization header. Without one, the practice API answers 401:

Bash
curl -s -o /dev/null -D - http://127.0.0.1:8000/api/private

The response headers start with HTTP/1.1 401 Unauthorized and include WWW-Authenticate: Bearer. Do not type a real token on the command line with -H. The command is saved in your shell history, and other users on the machine can read it from the process list while curl runs. Put the header in a private file instead. The umask makes the file readable only by you from the moment it exists, and -H @file tells curl to read headers from it. The token here is the practice server's fake one. For a real service, type or paste yours into the file with an editor:

Bash
(umask 077; printf 'Authorization: Bearer demo-token\n' > auth.txt)
ls -l auth.txt
curl -sS -H @auth.txt http://127.0.0.1:8000/api/private

The listing starts with -rw-------, and the call returns {"secret": "the cake is real"}. For HTTP basic authentication, -u user makes curl ask for the password on the terminal, which keeps it out of your history. Environment variables are not safe from the process list on every system, so prefer a file.

Check it worked

Bash
curl -s -o /dev/null -w '%{http_code}\n' -H @auth.txt http://127.0.0.1:8000/api/private

The output is 200.

Step 9 · Follow redirects

A redirect answers with a 3xx status and a Location header, and a browser follows it. curl does not unless you ask:

Bash
curl -s -o /dev/null -D - http://127.0.0.1:8000/old-items
curl -s -L -o /dev/null -w '%{http_code} %{url_effective}\n' http://127.0.0.1:8000/old-items

The first command shows HTTP/1.1 301 Moved Permanently and a Location: /api/items header. The second, with -L, follows it and prints 200 http://127.0.0.1:8000/api/items. %{url_effective} is the address curl ended on. curl follows at most 50 redirects by default, and --max-redirs changes that. Be careful with -L on requests that carry credentials: curl sends your Authorization header only to the first host unless you pass --location-trusted.

Step 10 · Measure where the time goes

-w can print timings, in seconds. This shows the cost of connecting and the total, for a request that the server delays by about a second:

Bash
curl -s -o /dev/null -w 'connect=%{time_connect} first_byte=%{time_starttransfer} total=%{time_total}\n' 'http://127.0.0.1:8000/api/slow?delay=1'

The total is a little over 1 second, and so is first_byte, and connect is close to zero. If connect is large, the network is slow. If first_byte is large and connect is small, the server took long to answer. That tells you where to look. %{time_namelookup} and %{time_appconnect} (TLS) complete the picture for a real HTTPS address.

Step 11 · Set timeouts and retries

Without limits, a stuck server leaves curl waiting. Set --connect-timeout for the connection and -m (--max-time) for the whole request:

Bash
curl -sS -m 1 'http://127.0.0.1:8000/api/slow?delay=3' || echo "curl failed with status $?"

After a second, curl prints curl: (28) Operation timed out after ... and the status is 28. A refused connection is status 7. Check it with a port nobody listens on:

Bash
curl -sS --connect-timeout 2 http://127.0.0.1:9 || echo "curl failed with status $?"

The message is curl: (7) Failed to connect to 127.0.0.1 port 9 .... --retry repeats a request after a transient failure: a timeout, or a response with status 408, 429, 500, 502, 503 or 504. When the server sends Retry-After, curl waits that long. The practice route fails twice with 503 and then succeeds:

Bash
curl -sS --retry 3 --fail-with-body http://127.0.0.1:8000/api/flaky

curl waits the second the server asked for after each 503, and you may see the two error bodies and their curl: (22) lines go by. The last output is {"ok": true}. Only retry requests that are safe to repeat. A POST that creates something may create it twice.

Step 12 · Read the verbose output

When a request fails in a way you cannot explain, -v shows the whole conversation. Lines starting with > are what curl sent, lines starting with < are what the server replied, and lines with * are curl's own notes about connecting:

Bash
curl -sv http://127.0.0.1:8000/api/items/1 2>&1 | grep -E '^(\*   Trying|> |< )'

Read the first lines of the request, which look like > GET /api/items/1 HTTP/1.1, > Host: 127.0.0.1:8000, > User-Agent: curl/8.18.0 and > Accept: */*, and the reply, < HTTP/1.1 200 OK with its headers. Without the grep, -v also prints the body. Verbose output is on stderr, which is why the example adds 2>&1. For HTTPS it also shows the TLS handshake and the certificate. --trace-ascii - goes further and shows the bytes.

Check these things first when something is wrong:

  • Is the address what you meant? The Host: line and the GET path show it.
  • Did a header you wanted go out? Look for it among the > lines. A header with an empty value is not sent.
  • Did the body go out as intended? Add --trace-ascii - and read the lines after => Send data.
  • Did the server answer with a redirect or an error that curl hid? Add -i.

Troubleshooting

  • curl: (7) Failed to connect means nothing is listening at that address and port. Check that the server is running in the second terminal.
  • curl: (3) URL rejected: Bad hostname or Malformed input often means an unquoted & or a space in the address. Quote the URL.
  • curl: (60) SSL certificate problem on a real HTTPS address means curl cannot validate the certificate. Do not fix it with -k, which turns validation off. Fix the certificate or the clock, or give curl the right CA file with --cacert.
  • curl: (52) Empty reply from server means the server closed the connection without answering. Read the server's log.
  • A POST returns 415 or 400 because the JSON was sent as a form. Use --json, or add -H 'Content-Type: application/json'.

Step 13 · Stop the server and clean up

Press Ctrl+C in the second terminal. Then delete the folder with the practice API, the token file and the items:

Bash
cd ~
rm -rf ~/curl-demo

If you installed jq only for this tutorial, remove it with sudo apt remove jq.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.