Technical
API Examples That AI Agents Can Use
Build complete API examples with explicit prerequisites, authorization, response states, retry boundaries and executable local checks.
By Mohammad Alshaikhusain
Published
Sources checked
An API example becomes useful to a developer or coding agent when it supplies the whole task: where to run it, what authorizes the request, what inputs it needs, what success means and what to do after failure. Verify those claims with executable assertions rather than judging whether the code looks plausible.
This article includes a small local teaching API and its test file. The tests exercise real HTTP requests on your machine using fake data. They establish the behavior of that fixture, not the security or reliability of a production service, and not how often an agent will recommend your product.
Start with a bounded task and success condition
A task such as “integrate events” leaves too much room for interpretation. A better example says: “Submit one event to the local v1 endpoint, obtain an accepted receipt, replay the same request without creating another receipt, and reject a changed payload that reuses the key.”
That statement tells the implementer what to do and the reviewer what to check. It also prevents a successful HTTP response from being mistaken for a complete business process.
For this fixture, the contract is:
| Item | Local teaching contract |
|---|---|
| Runtime | Node.js with built-in fetch; independently checked on Node 24.19.0 |
| Network | Loopback only, 127.0.0.1; no external API calls |
| Operation | POST /v1/events |
| Credential | Fixed fake bearer value local-demo-only |
| Body | Non-empty event name plus an object named properties |
| Replay rule | Same key and exact request-body text returns the original receipt |
| Conflict | Same key with a different valid body returns 409 |
| Successful state | Accepted, not delivered |
| Storage | In-memory for the current process; restart erases receipts and keys |
This is intentionally a narrow contract. There is no external destination, delivery worker, database, account system or real OAuth flow. A production tutorial should name those prerequisites where they actually exist instead of letting the example suggest they are unnecessary.
Download and run the local example
Save both files in the same directory:
Inspect the files, then run:
node --version
node api-example.test.mjs
The test file starts the server on an available loopback port, submits requests, checks the results and closes the server. It requires permission to bind a local port. If your sandbox prevents that, the listener can fail before any request is exercised; that is an environment restriction rather than a failed assertion about the API contract.
No dependency installation is needed. The file uses Node built-ins, and the request client uses built-in fetch. The recorded check was on Node 24.19.0, not an exhaustive compatibility test across Node versions. Use a currently supported runtime for your own tooling and rerun the checks in that environment.
On September 17, 2026, the independent run completed all 11 scenario checks. The output includes the runtime and a list of passed scenarios rather than claiming the fixture is production-ready.
Inspect the request instead of hiding it behind an SDK
You can also run the server manually:
node api-example.mjs
This uses loopback port 4319. Keep that terminal open. If the port is already occupied, use the automatic test file or deliberately change the manual listener and matching request URL. Do not silently send the request to an unrelated local service.
In a second terminal, submit the request:
curl -i http://127.0.0.1:4319/v1/events \
-H 'Authorization: Bearer local-demo-only' \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: example-001' \
--data '{"name":"workspace.created","properties":{"workspace_id":"ws_example_001"}}'
On a fresh fixture process, the JSON response is:
{"event_id":"evt_1","status":"accepted"}
The HTTP status is 202. Keep the same key and exact body when replaying this example. On an already-used server, the identifier can differ because the process assigns IDs sequentially. The stable claim is that an identical valid replay returns the original receipt, not that every request in every session is evt_1.
This plain HTTP representation exposes method, path, media type, authorization, replay key and body together. A corresponding SDK example should identify its package version and show which client call implements the same contract. A short SDK call is useful only if the surrounding setup supplies the information it hides.
Explain the credential boundary plainly
The fixed value in this fixture is public fake data. It exists to let the test distinguish accepted credentials from rejected ones. It is not a secret and provides no meaningful protection against someone who can read the example.
A production example needs the actual credential issuance procedure, allowed scope, storage location and transport requirements. Bearer credentials belong in the Authorization scheme defined by the relevant specification; that specification requires TLS for their use. The fixture's plain HTTP listener is a local teaching exception using a fake value, not a pattern for sending real bearer credentials over a network. Bearer-token authorization
When writing a real tutorial, state whether the credential belongs to a user, project, workspace or service account. Explain which operations it authorizes. Do not replace this with “get your API key” when several credentials exist and only one fits the task.
The authentication documentation guide treats that setup as a complete reader task. Keep the essential permission boundary beside the request even when linking a longer setup page.
Distinguish acceptance from completion
HTTP 202 represents acceptance for processing, not proof that processing completed. A real asynchronous service may need a status endpoint, webhook or other completion evidence. HTTP 202 semantics
The local fixture offers receipt readback:
curl -i http://127.0.0.1:4319/v1/events/evt_1 \
-H 'Authorization: Bearer local-demo-only'
Use the identifier returned by your actual request. The response remains accepted. There is no downstream delivery mechanism, so waiting longer will not change it to delivered.
That limitation is part of the example. It prevents the documentation from implying a lifecycle the code does not implement. If adapting the example to a real service, write separate assertions for acceptance and completion, including the conditions under which completion can fail.
A coding agent saying “integration complete” is not the same as those assertions passing. Preserve the output or resulting state that demonstrates the claimed outcome.
Define replay behavior before recommending retries
POST requests do not acquire safe replay behavior merely because a client sends a header named Idempotency-Key. The server must implement a documented contract. HTTP's definition of idempotence concerns the intended effect of repeated requests, not a universal interpretation of a custom header. HTTP idempotence
This fixture implements a deliberately simple rule:
- Validate the credential, content type, key and event body.
- If the key has no record, create a receipt and save the original body text.
- If the key exists with exactly the same body text, return the saved receipt.
- If the key exists with a different valid body, return 409.
Exact text matters. Changing JSON whitespace or property ordering can produce a conflict even when the parsed objects look equivalent. The rule is easy to demonstrate, but it is not an endorsement of text equality as the best production design.
Keys are scoped only to this single-token process. There is no expiry policy, durable storage or distributed coordination. A restart loses the record, so a retry after restart is outside the example's replay guarantee.
A production service must define those boundaries explicitly. Stripe's idempotency documentation, for example, describes its own behavior for retained results and parameter comparison. Do not copy assumptions from that service into another API without checking its contract. Stripe's idempotency behavior
After a timeout, the caller may not know whether the request succeeded. Preserve the original request and follow the service's documented recovery procedure. Creating a new key automatically can defeat duplicate protection; reusing an old key with a changed operation can cause a conflict.
Give errors an action, not just a status
The local fixture's error shape is a small JSON object with an error field. It is not presented as an implementation of the Problem Details standard. If choosing that standard for a real API, implement its actual representation and extension rules. Problem Details for HTTP APIs
| Fixture outcome | What the caller should investigate |
|---|---|
| 401 invalid_token | Credential value; the response includes a bearer challenge |
| 415 json_required | Content-Type must identify JSON |
| 400 invalid_json | Request body is not valid JSON |
| 400 invalid_event | Name or properties do not satisfy this small contract |
| 400 idempotency_key_required | Key is missing, blank or exceeds the fixture's allowed length |
| 409 key_reused_with_different_body | Existing key identifies a different request body |
| 404 not_found | Operation or receipt does not exist in this fixture |
The next action depends on the cause. Repeating invalid JSON unchanged will not fix it. Retrying with the same conflicting key and changed body will not turn it into the original operation. A missing receipt after restart reflects the fixture's memory-only storage, not proof that a production service should forget accepted work.
The fixture also includes a small body-size limit, but the 11-scenario test does not certify every parser edge case or hostile traffic condition. Do not deploy this server as a hardened service. The API error guide explains how to document production failure handling more fully.
Test the claims that matter to the example
The executable check covers these scenarios:
| Scenario | Assertion established by the local run |
|---|---|
| Valid request | 202 and the expected accepted receipt |
| Identical replay | Same receipt returned |
| Different valid body with existing key | 409 |
| Invalid credential | 401 with authentication challenge |
| Invalid JSON | 400 |
| Invalid event fields | 400 |
| Missing replay key | 400 |
| Wrong media type | 415 |
| Receipt lookup | Stored receipt returned |
| Unknown receipt | 404 |
| Two concurrent requests with one key | Both resolve to the same receipt ID |
The concurrency scenario exercises this local single-process implementation. It does not prove distributed locking or behavior across multiple service instances. Similarly, a test with an invalid fake credential is not a penetration test of a real authentication system.
Keep the test file next to the example when publishing. If a writer changes the request or response in the article, rerun the check and compare the displayed sample with the tested version. A passing old fixture does not validate a newly edited code block automatically.
Adapt the pattern to a real integration
For a real product tutorial, replace the fictional server with an authorized sandbox and record the environment. Provide actual account setup, a safe test resource, a versioned SDK or API contract, and cleanup instructions for resources created during the exercise.
Define the state that proves completion before running the task. For example, a created object should be retrievable with the expected fields; an asynchronous delivery should have the documented completion evidence. Avoid relying on a console message produced by the integration script itself as the only success criterion.
Use a limited task with known side effects. A tutorial should not require an agent to improvise permissions, send messages to real customers or modify production data merely to make a sample pass. State what the example will create and how to remove it.
See the integration tutorial guide for organizing the complete setup and the context-preservation guide for keeping critical boundaries beside each instruction.
Questions before publishing an API example
Does a passing example prove an agent will choose our product?
No. It demonstrates the tested implementation behavior. Spontaneous selection, recommendation and successful use are different outcomes. Measure them separately if each matters to your product.
Should every example include a server?
No. An existing authorized sandbox may be more representative. A local fixture is valuable when you need a reproducible explanation without external credentials or real side effects. Label which environment was tested and what it leaves out.
Can we call this production-ready?
No. This fixture deliberately omits real authentication, TLS, persistent state, distributed concurrency control and delivery processing. It is useful because its teaching scope is small and inspectable, not because it solves all operational concerns.
What should the release record contain?
The article and fixture revision, runtime, command, scenario results, date and limitations. Preserve failed checks too. On a product change, update the prose, code and assertions together rather than changing only the publication date.
Sources and verification
Primary references checked September 17, 2026: HTTP semantics, bearer authorization, Problem Details and Stripe's product-specific idempotency documentation. The local fixture was independently executed on Node 24.19.0 on that date with all 11 recorded scenarios passing. No external API or production account was used. This is implementation evidence for the downloadable fixture, not evidence of AI citation or recommendation improvement.
Source references
The following sources were checked September 17, 2026. Illustrative examples and proposed procedures are identified separately in the article.
- Bearer-token authorization. Checked September 17, 2026.
- HTTP 202 semantics. Checked September 17, 2026.
- HTTP idempotence. Checked September 17, 2026.
- Stripe's idempotency behavior. Checked September 17, 2026.
- Problem Details for HTTP APIs. Checked September 17, 2026.
Continue reading
Explore GEO with Jam
See how Jam approaches AI visibility research and content improvements for developer-tool teams.
Explore Jam for GEO