API Testing with curl: Request Templates for Headers, JSON, Authentication, and Errors
curlAPIsHTTPcommand linebackend development

API Testing with curl: Request Templates for Headers, JSON, Authentication, and Errors

bbeneficial.cloud Editorial Team
2026-12-01
7 min read

Copyable curl templates for testing APIs with JSON, headers, authentication, uploads, diagnostics, and practical error troubleshooting.

Testing an API with curl gives you a fast, repeatable way to inspect requests without opening a browser or writing a client application. This guide provides copyable templates for GET and POST requests, JSON bodies, headers, authentication, uploads, redirects, timeouts, verbose diagnostics, and response inspection, plus a troubleshooting workflow you can reuse during development and incident investigation.

Overview

curl is useful for checking whether an endpoint is reachable, confirming that request headers and bodies are correct, and separating client-side problems from server-side responses. It fits well into a cloud-native developer workflow because the same basic commands can run locally, in a container, or in a CI job.

A reliable API test should make five things visible:

  • Target: the HTTP method and complete URL, including query parameters.
  • Headers: content type, authorization, correlation IDs, and other required metadata.
  • Body: valid JSON, form data, or a file payload when the endpoint expects one.
  • Transport behavior: redirects, TLS negotiation, connection timing, and timeouts.
  • Response evidence: status code, response headers, body, and useful timing information.

Start with the smallest request that can answer your question. Add headers, authentication, and diagnostic flags one at a time. This keeps API debugging with curl understandable and makes it easier to identify which change affected the result.

Template structure

The following templates use a placeholder base URL. Replace https://api.example.test, paths, IDs, and tokens with values from your own environment.

Basic GET request

curl --request GET \
  --url 'https://api.example.test/v1/users?status=active'

GET is the default method, so this shorter form is equivalent:

curl 'https://api.example.test/v1/users?status=active'

Quote URLs when they contain &, question marks, brackets, or other characters that your shell might interpret.

POST JSON

curl --request POST \
  --url 'https://api.example.test/v1/users' \
  --header 'Content-Type: application/json' \
  --data '{"name":"Ada Lovelace","role":"developer"}'

For a JSON API, Content-Type tells the server how to interpret the request body. If the API also requires an explicit response format, add an Accept header:

curl --request POST \
  --url 'https://api.example.test/v1/users' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"name":"Ada Lovelace"}'

Send JSON from a file

curl --request POST \
  --url 'https://api.example.test/v1/events' \
  --header 'Content-Type: application/json' \
  --data @event.json

Using a file avoids complicated shell quoting and makes larger test payloads easier to review. Keep test fixtures free of real secrets and personal data.

Custom headers and bearer authentication

curl --request GET \
  --url 'https://api.example.test/v1/profile' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'X-Request-ID: local-debug-001' \
  --header 'Accept: application/json'

For local work, an environment variable is safer than repeatedly pasting a token into shell history:

export API_TOKEN='replace-me'
curl --url 'https://api.example.test/v1/profile' \
  --header "Authorization: Bearer ${API_TOKEN}"

Do not commit tokens to scripts or share verbose output that includes authorization headers. Treat access tokens, API keys, cookies, and signed URLs as sensitive values.

Form data and file uploads

Use --form when an endpoint expects multipart/form-data rather than a JSON body:

curl --request POST \
  --url 'https://api.example.test/v1/uploads' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --form 'description=Build artifact' \
  --form 'file=@./dist/app.zip'

Let curl construct the multipart boundary. Manually setting a multipart Content-Type header can produce a boundary mismatch.

Redirects, timeouts, and verbose output

curl --location \
  --max-time 15 \
  --request GET \
  --url 'https://api.example.test/v1/health'

--location follows redirects. Use it deliberately, especially when a request carries credentials: understand where the redirect goes before sending sensitive headers. --max-time prevents a test from waiting indefinitely.

curl --verbose \
  --connect-timeout 5 \
  --max-time 20 \
  --url 'https://api.example.test/v1/health'

--verbose shows connection and request details useful for debugging TLS, proxies, redirects, and headers. Avoid posting this output publicly if it contains credentials or private hostnames.

Inspect response headers, status, and timing

Include response headers with the body:

curl --include \
  --url 'https://api.example.test/v1/users/42'

Print only the HTTP status after the response body:

curl --silent --show-error \
  --output response.json \
  --write-out '\nHTTP %{http_code}\n' \
  'https://api.example.test/v1/users/42'

Measure connection and total request time:

curl --silent --output /dev/null \
  --write-out 'status=%{http_code} connect=%{time_connect}s total=%{time_total}s\n' \
  'https://api.example.test/v1/health'

On Windows shells, quoting and output redirection can differ. If a multiline example does not work, place the command on one line or adapt line continuation to the shell you are using.

How to customize

Turn a generic request into a useful test by changing one layer at a time:

  1. Set the environment: define the base URL and, where appropriate, a token variable rather than embedding values in every command.
  2. Confirm the method and path: compare the command with the API contract, including path parameters and query-string encoding.
  3. Add required headers: begin with Accept and Content-Type, then add authorization, tenant, version, or tracing headers.
  4. Validate the body: format JSON before sending it and check commas, quotes, data types, and required fields. A JSON formatter can make malformed payloads easier to spot.
  5. Add diagnostics: use --include for response headers, --verbose for transport details, and --write-out for consistent status and timing.
  6. Make failure explicit: use --fail-with-body when you want a non-success HTTP response to produce a failing command while preserving the server response body for inspection.

When shell quoting becomes difficult, move the payload into a file. This is especially useful for nested JSON, multiline strings, regular expressions, and values containing apostrophes. For query parameters supplied by users or scripts, encode them rather than concatenating untrusted text directly into a URL.

A JWT decoder can help inspect non-secret claims such as expiration and audience during development, but decoding a token does not verify its signature. Use the API or its identity provider to validate authentication behavior, and never paste production credentials into an untrusted online tool.

Examples and troubleshooting

Test a protected update

curl --request PATCH \
  --url 'https://api.example.test/v1/projects/123' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Content-Type: application/json' \
  --data '{"name":"Updated project"}' \
  --include

If the response is unexpected, first determine whether the server received the intended method, URL, headers, and body. Then compare the response status with the API contract.

SymptomLikely areaWhat to check
Could not resolve hostDNS or URLCheck the hostname, local DNS, VPN, and spelling. Quote the complete URL.
Connection refusedService or portConfirm the service is running, the port is exposed, and the URL uses the expected scheme and port.
Operation timed outNetwork path or server latencyTry --verbose, set a bounded timeout, and check proxy, firewall, and service logs.
401 UnauthorizedAuthenticationCheck token presence, expiration, issuer, audience, and the exact Authorization scheme.
403 ForbiddenAuthorizationConfirm the identity has the required role, scope, tenant, or resource permission.
404 Not FoundRoute or resourceCheck the HTTP method, API version, path parameters, and selected environment.
415 Unsupported Media TypeRequest formatSet the correct Content-Type and send the body format the endpoint documents.
422 or 400 responseValidation or syntaxInspect the response body, format the JSON, and verify required fields and data types.
curl exit code with no HTTP responseClient or transportUse --show-error and --verbose to distinguish TLS, DNS, timeout, and connection failures.

For browser-only problems such as CORS, compare the command with the browser's request in the Network tab. A successful curl request does not automatically prove that a browser request will be permitted, because browsers apply additional security rules.

When to update

Revisit these templates whenever the API contract, authentication flow, deployment environment, or shell workflow changes. Update the base URL when moving between local, staging, and production systems; review headers when versioning or tenant rules change; and replace payload fixtures when required fields or response formats change.

Keep a small, safe smoke-test set for each important endpoint:

  1. Run a health or unauthenticated read request.
  2. Run one authenticated request with a test identity.
  3. Run a valid write request against a disposable resource.
  4. Run an intentional invalid request and record the expected error shape.
  5. Capture status, response body, and timing without exposing secrets.

Before adding a command to CI, replace interactive credentials with the CI system's secret mechanism, constrain permissions, and avoid printing headers that contain sensitive values. If a command becomes part of a regression suite, pin its inputs and document the expected status code so a future API change produces a clear, actionable failure.

For related debugging workflows, compare API responses with the browser's request details in the Chrome DevTools Network Tab Guide. When malformed payloads or query results are involved, the JSON and SQL Formatting Workflow provides a useful companion process.

Related Topics

#curl#APIs#HTTP#command line#backend development
b

beneficial.cloud Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.