On this page
The short answerWhy curl examples breakClassify blocks before running themBuild a runnable local harnessValidate bodies and response claimsKeep credentials out of documentationBound network failuresHow the engine handles HTTP blocksTriage a failed checkAdd the check to your workflowWhere DocsAlive fitsThe sources we checkedFAQThe short answer
Test HTTP examples as requests with explicit expectations: validate the body, make the request against a controlled endpoint, check its status and inspect the fields the documentation promises. The most important detail is that curl normally exits successfully even when a server returns 400 or 404. Use --fail-with-body or -f when an HTTP error should fail the command, and test response content separately.
API documentation, READMEs and quickstarts often give readers a curl command as their first working interaction with a service. That command is a compact contract: it names a host, path, method, headers and body, and usually implies a particular response. Each part can drift independently.
DocsAlive can run supported documentation blocks and classify the resulting failures. Its treatment depends on the fence label and the contents of the block. An http fence and a shell block containing curl do not have identical status handling, and a displayed response is not checked against the server’s response. This guide shows a separate local test for the request and response, then explains the engine’s behavior in version 0.6.3.
For the broader API reference workflow, see testing API reference documentation. For examples that require private access, see testing credential-dependent examples.
Why curl examples break
A request can remain syntactically valid while the API contract changes around it. A route can move from one version to another, a path can be renamed, or a host can change. A POST example may still point to a route that now expects another method. A service can add a required field or change the expected shape of an existing one.
Authentication can drift too. A page may still show an old authorization scheme after the service changes it, or it may omit a required header. A command that worked for its author can fail for readers because it depended on a real key from the author’s environment.
The body is another source of failure. JSON with a trailing comma is invalid, and a missing shell quote can prevent the command from reaching curl at all. A valid JSON string can still be sent with the wrong Content-Type, or contain fields the current API rejects. A response sample can become stale even when the request continues to work.
A build of the documentation site will usually render all of these examples. Rendering proves that a fence can be displayed; it does not establish that the request succeeds or that the response shown to a reader is current.
The exit-status trap
By default, curl treats a completed HTTP transfer as successful even when the HTTP status is an error. A command can receive a 404 or 400 and still exit with status zero. A runner that checks only the process exit status will therefore call that broken request green.
--fail-with-body makes curl return exit code 22 for HTTP error responses while retaining the response body. -f, also written --fail, returns exit code 22 without printing the body. The options are mutually exclusive. The curl manual cautions that -f is not fail-safe: authentication responses such as 401 and 407 can slip through. An explicit status check remains useful when the exact status matters. See the curl manual and curl exit-code guide.
--fail-with-body is available in curl 7.76.0 and later. The local harness below uses curl 8.x. It also checks %{http_code} because a successful transfer alone does not establish that a GET returned 200 or a creation request returned 201.
Classify blocks before running them
A fence label tells a renderer how to present a block. It does not always tell a test what the author intended the reader to execute.
| Block | Suitable treatment | What remains to check |
|---|---|---|
| Runnable request against a public or sandbox endpoint | Execute with a bounded timeout and explicit status expectations | Whether the response fields still match the documented contract |
| Credential-gated request | Keep the credential out of the page; run a separate authorized check if available | Whether the documented access and permissions are sufficient |
Request against fictional api.acme-docs-demo.test |
Treat the host as an illustration, not a live service | Whether the request’s shape is representative |
| Response sample | Keep it separate from the command and compare stable claims in your own test | Whether variable fields are described as variable |
http message block |
Parse and send it only when its host and body are intended to be runnable | Status, content and the assumptions made by the sender |
| Fragment or omitted setup | Record the prerequisite or make a complete companion example | Whether a reader can assemble the full request |
A public endpoint is not automatically a safe test target. Choose an operation and dataset that are appropriate for repeated CI runs. A sandbox can give a more representative integration check than a stub, while a stub gives a fast and predictable check of the documented request’s local mechanics.
Build a runnable local harness
The following two files form a small local test. They need Python 3, bash, curl and jq. Save them in the same directory as stub.py and test-curl.sh, then run bash test-curl.sh from that directory.
The server binds only to 127.0.0.1:18765. It supplies the routes used by the test: a widget lookup, widget creation, a private route and a 404 for other paths. It is a test fixture, not evidence that a production service implements the same contract.
# stub.py
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class Handler(BaseHTTPRequestHandler):
def send_json(self, status, value):
body = json.dumps(value).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def do_GET(self):
if self.path == "/v1/widgets/w_123":
self.send_json(200, {"id": "w_123", "name": "demo"})
elif self.path == "/v1/private":
self.send_json(401, {"error": "unauthorized"})
else:
self.send_json(404, {"error": "not found"})
def do_POST(self):
if self.path != "/v1/widgets":
self.send_json(404, {"error": "not found"})
return
try:
length = int(self.headers.get("Content-Length", "0"))
value = json.loads(self.rfile.read(length))
name = value["name"]
except (ValueError, KeyError, TypeError):
self.send_json(400, {"error": "invalid JSON"})
return
self.send_json(201, {"id": "w_456", "name": name})
if __name__ == "__main__":
ThreadingHTTPServer(("127.0.0.1", 18765), Handler).serve_forever()
#!/usr/bin/env bash
# test-curl.sh
set -euo pipefail
work_dir=$(mktemp -d)
server_pid=
cleanup() {
if [[ -n "$server_pid" ]]; then
kill "$server_pid" 2>/dev/null || true
wait "$server_pid" 2>/dev/null || true
fi
rm -rf "$work_dir"
}
trap cleanup EXIT
python3 stub.py >"$work_dir/server.log" 2>&1 &
server_pid=$!
ready=0
for _ in {1..50}; do
if curl -sS --fail-with-body --max-time 1 \
http://127.0.0.1:18765/v1/widgets/w_123 \
>"$work_dir/ready.json" 2>/dev/null; then
ready=1
break
fi
if ! kill -0 "$server_pid" 2>/dev/null; then
cat "$work_dir/server.log" >&2
exit 1
fi
sleep 0.1
done
if [[ "$ready" != 1 ]]; then
cat "$work_dir/server.log" >&2
exit 1
fi
status=$(curl -sS --fail-with-body --max-time 5 \
-o "$work_dir/get.json" -w '%{http_code}' \
http://127.0.0.1:18765/v1/widgets/w_123)
[[ "$status" == 200 ]]
jq -e '.id == "w_123" and .name == "demo"' \
"$work_dir/get.json" >/dev/null
body='{"name":"demo"}'
printf '%s\n' "$body" | python3 -m json.tool >/dev/null
status=$(curl -sS --fail-with-body --max-time 5 \
-o "$work_dir/post.json" -w '%{http_code}' \
-H 'Content-Type: application/json' \
-d "$body" http://127.0.0.1:18765/v1/widgets)
[[ "$status" == 201 ]]
jq -e '.id == "w_456" and .name == "demo"' \
"$work_dir/post.json" >/dev/null
printf '%s\n' 'GET and POST checks passed'
The readiness loop avoids assuming the server is available immediately after it starts. The cleanup trap stops the server and removes temporary files even if a check fails. If the port is already occupied, stop the other service before running the harness; otherwise the test could reach a different process.
The GET check asserts both the exact status and two response fields. The POST check validates the request body with python3 -m json.tool before sending it, then verifies the creation status and returned fields with jq -e. A false jq expression exits non-zero, so the shell stops. The Python server documentation and jq manual describe the tools used here.
In a real repository, keep the commands under test close enough to the documentation that a change to one prompts a review of the other. A copied test can itself drift. Where practical, extract the documented command or share a fixture, while retaining a readable example for the reader.
A broken path and two different reports
The following command is broken for the stub above: /v1/widget is not the creation route. With the server running, it receives a 404, but curl exits zero because the command does not request HTTP failure handling.
curl -sS -X POST -H 'Content-Type: application/json' \
-d '{"name":"demo"}' http://127.0.0.1:18765/v1/widget
A runner that checks only the curl exit status reports success. A curl or shell fence in DocsAlive also passes in this situation. Add --fail-with-body, and curl exits 22; the engine reports a failure categorized as runtime-error for review. The explicit status and response assertions in the harness also make the mismatch visible when applied to the documented route.
A non-zero result still needs interpretation. A renamed route is a documentation problem if the page promises that route for the tested API version. A temporary outage, an inaccessible sandbox or a missing credential needs a different response. Preserve the status, command and relevant error while avoiding secrets in logs.
Validate bodies and response claims
Single quotes around a literal JSON body are a useful bash pattern because double quotes inside the JSON remain intact. That does not make the JSON valid: a trailing comma or missing value still needs a parser to detect it. Validate the exact body that will be sent, as the harness does, rather than a separately retyped version.
curl also offers --json as a shortcut. It sends the supplied data using the corresponding binary-data behavior and adds JSON Content-Type and Accept headers. It does not validate that the supplied data is JSON. The option was added in curl 7.82.0. If your audience may have an older curl, document the requirement or use the more widely available header and data options.
Keep a response sample in its own block after an introduction such as “Response:”. Decide whether it promises exact values or illustrates a shape. IDs, timestamps and generated tokens often vary; a test can assert stable keys and types while explaining which values a reader should expect to differ.
DocsAlive recognizes an output block introduced this way and skips it. It does not compare that block with the HTTP response. Printed output is compared only for pycon or python-repl sessions. Use your own assertions for HTTP status, JSON fields and any other response contract.
Keep credentials out of documentation
Use a clearly named placeholder environment variable in a published command, and explain where a reader obtains and supplies its value. ACME_API_KEY, Acme SDK and acme-sdk are fictional names in this guide. Never paste a real key into a page, a test fixture or a command transcript.
For a separate integration check, use a sandbox key stored in CI secrets, with the minimum permissions and lifecycle appropriate to that sandbox. Avoid printing the key in failure logs. Record which environment and account the check uses so a failure can be reproduced by an authorized maintainer.
DocsAlive detects common credential placeholders, including $ACME_API_KEY, and skips the block as needing credentials. It does not currently run examples with customer-provided test credentials. A credential-gated example therefore needs a separate authorized test if you need evidence of the complete flow.
Bound network failures
Use --max-time to limit each transfer. A hung request should not hold a documentation check indefinitely. --retry can retry transient failures such as timeouts and selected HTTP statuses; curl’s default is zero retries. Choose a small retry count appropriate to the endpoint and operation, and be careful with operations that create or modify data.
Retries improve resilience to intermittent upstream failures, but they can also conceal a recurring service problem. Keep the final failure visible and distinguish a network incident from a changed documentation contract. The HTTP semantics specification is useful when deciding what a status code means for the operation.
A local stub answers a narrower question: can the documented request be constructed and checked under controlled conditions? A sandbox check answers whether the real integration works in that environment. Use both when the integration matters and the sandbox permits repeatable testing.
How the engine handles HTTP blocks
In engine 0.6.3, fence form changes the plan. Review the report’s status and reason for every important block; a green result alone does not establish response content.
| Block form | What the engine does in 0.6.3 |
|---|---|
curl, bash, sh, shell or zsh |
Runs it as shell. curl’s own exit status controls success, so 400 and 404 can pass without --fail or --fail-with-body. |
console or shell-session |
Runs lines beginning with $; other lines are treated as output and are not compared. |
http |
Parses a supported method, URL, headers and optional body, then sends with curl. A body causes an application/json content type to be added. |
http response of 400 or above |
Fails. 401 and 403 are categorized as needing credentials; other 4xx results need review as runtime-error; 5xx and connection failures are categorized as external network results. |
http response in the 2xx range |
Passes based on the request result; the response body is not compared. |
| Placeholder credential | Skips a shell or curl block as needing a placeholder, categorized needs-credentials. |
| Recognized output block | Skips it as output-block; its contents are not validated. |
Network-requiring block with --no-network |
Skips it as network disabled, including blocks containing HTTP URLs. |
| Unmapped fence label | Reports pass without running or parsing it; this is a known limitation. |
An http fence accepts GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS request lines, optionally followed by HTTP/1.1. It reads headers until a blank line and treats the remainder as a body. A relative path paired with a Host header is sent over HTTPS, so that form cannot represent a plain HTTP-only local server in this engine. The default per-block timeout is 60 seconds.
The engine’s status categories help separate evidence from a decision. A failed 404 in a shell block with --fail is a review item, not automatically a filed documentation bug. Inspect the report and reproduce against the intended version before changing the page.
Triage a failed check
| Finding | Investigate | Possible action |
|---|---|---|
| 404 on a documented route | API version, host and path | Update the route or restore the intended compatibility |
| 400 on a body | JSON syntax, required fields and content type | Correct the body and add a focused assertion |
| 401 or 403 | Auth scheme, permissions and sandbox credential | Correct the instructions or repair the authorized test setup |
| 5xx, timeout or name resolution failure | Service health and network availability | Retry under the agreed policy and investigate the environment |
| Status passes but a jq assertion fails | Changed response field or stale sample | Decide which contract is intended and update the responsible side |
| Placeholder or fictional host | Whether the page labels the example clearly | Keep it illustrative and add a separately runnable fixture if needed |
| Output block skipped | Whether a reader relies on its values | Add a separate response assertion |
A useful finding includes the page, line, tested API version, expected result and observed status. Redact credentials and sensitive response data. For the product’s categories and report fields, see findings.
Add the check to your workflow
Run the local harness on changes to the relevant examples and server contract. Run a sandbox check on a schedule and around releases if the sandbox is stable enough for that purpose. A release check should identify the API version and environment it exercised; a local stub alone cannot prove a deployed service is compatible.
Use the following checklist in a review:
[ ] Classify each request, response sample and message block.
[ ] State the API version, host and prerequisites.
[ ] Use --fail-with-body or -f when HTTP errors should fail curl.
[ ] Check the exact expected status where it matters.
[ ] Validate the request JSON before sending it.
[ ] Check stable response fields with a separate assertion.
[ ] Label fictional hosts and illustrative values.
[ ] Keep real credentials in an appropriate secret store.
[ ] Bound transfers and choose a deliberate retry policy.
[ ] Review skipped blocks and external failures.
[ ] Re-run against the intended release or sandbox.
Where DocsAlive fits
DocsAlive extracts supported blocks, plans their treatment and runs executable examples in page order. It reports skips and categorizes failures so maintainers can distinguish likely documentation bugs from credential requirements, external failures and missing context. Its CLI can scan a local checkout or Git URL; execution must be requested with --execute.
Use its report to locate requests worth investigating, then retain a dedicated HTTP test for exact status and response assertions. A scan without execution is an extraction and planning pass. A scan with --no-network cannot verify URL-based requests. For a wider review of coverage, use the documentation testing checklist.
If your API examples live in a framework site, the guides to Starlight and Nextra explain how source layout and tabs affect coverage.
The sources we checked
These sources were read on November 11, 2026.
| Source | What it covers |
|---|---|
| curl manual | Failure options, JSON shortcut, status output, timeouts and retries |
| curl exit codes | How curl reports transfer failures |
Python http.server |
The local server used in the harness |
| jq manual | JSON assertions and exit status |
| HTTP semantics | HTTP methods and status semantics |
FAQ
Why can a curl command pass on a 404?
curl normally reports a successful transfer even when the server returns an HTTP error. Use --fail-with-body or -f when that response should fail the command, and check the exact status separately when it matters.
Does --json validate the request body?
No. It supplies data and JSON headers as a shortcut, but it does not parse the data as JSON. Validate the body separately before sending it.
Does DocsAlive compare an HTTP response with the sample?
No. A recognized response block is skipped as output, and its contents are not compared. Use a separate test to assert the status and stable response fields.
Can I test an example that needs a real key?
Use an authorized sandbox check with a key stored in CI secrets. DocsAlive classifies credential-dependent examples and does not currently run them with customer-provided test credentials.
What does an http fence check?
The engine sends the parsed request and treats responses of 400 or above as failures. It does not compare the response body with a displayed sample, and its relative-path form uses HTTPS with the Host header.
Is a local stub enough?
A stub is useful for repeatable checks of request construction and assertions. It does not establish that a deployed API or its authentication works, so use an authorized integration check for those claims.




