REST API Example: Request, Response and Auth Explained

Key takeaways
A REST call is a method, URL, headers and an optional body; the response is a status code, headers and a representation. Keep the resource in the path, use query parameters only to shape reads, and send writes in a JSON body. 401 means the credentials are wrong, 403 means the role is not allowed, 422 means the data failed validation. POST is not idempotent: retry a timed-out create only with an idempotency key the API supports, or check the collection first. A valid token is not authorization, so test cross-workspace reads and writes on purpose.
The curl snippet from the docs worked first time. You pasted it, swapped in your token, got a 201 Created back, and shipped the integration. Three weeks later the same call runs from a nightly job, the connection drops after the server has already written the row, your retry code fires, and the links page now shows three copies of the same campaign URL.
That gap between the tutorial call and the production call is where most REST API examples stop. API use is near universal: Gartner's Hype Cycle for APIs, 2024 reports that 82% of survey respondents said their organizations used APIs internally, and 71% also used APIs provided by third parties such as SaaS vendors[1]. The calls that hurt you are rarely the ones you wrote yourself.
What follows is one resource, a short link, followed from the first byte of the request to the authorization check that decides whether you're allowed to touch it at all. Every header, status code and error body below is copyable, and the failure paths get as much room as the happy one.
What a REST API Example Shows#
A REST API call has a shape you can inspect: a client sends a method, URL, headers and, when needed, a body. The server replies with a status code, headers and a representation. That structure applies across APIs, whether the resource is a link, an order or a user record.
Roy Fielding formalized REST as an architectural style for networked systems in his 2000 doctoral dissertation. Its constraints include client-server separation, stateless communication, cacheable responses and a uniform interface (Fielding's dissertation[2]). Statelessness means each request carries the information the server needs to handle it. A load balancer can route requests to different server instances without relying on session state left by an earlier call.
REST is the default style for web APIs, and securing them is now its own discipline: the SANS Institute's 2024 Application Security & API Survey[3] looks at how organizations protect the applications and APIs they run.
The running example is a redirect and short-link management API with a /links resource. A link makes the request lifecycle concrete: clients can create, retrieve, update and delete it, while the server must validate input and enforce authorization. The example endpoint is https://api.example.com/v1/links.

A REST API example has six parts:
- Endpoint: the base URL plus a resource path, such as
https://api.example.com/v1/links. - Method:
GET,POST,PUT,PATCHorDELETE, selected according to the operation. - Headers: values such as
AuthorizationandContent-Type, plus request controls such asIdempotency-KeyorIf-Match. - Parameters: path segments, query-string values and fields in the request body.
- Response status code: the result the client uses to decide what to do next.
- Response headers and body: metadata such as
Location,ETagandCache-Control, along with the returned JSON.
For another public example of request and response structures, see the StalkChain REST endpoint documentation[4].
A Complete Request and Response Example#
A request is not finished when the server returns 201. The client still has to identify the created resource, handle a lost response without creating a duplicate, and avoid overwriting a newer edit.
Here is a create call for a short link:
bashcurl -X POST https://api.example.com/v1/links \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 7f3e9c2a-4b1d-4e8f-9c2a" \
-d '{"slug":"spring-sale","destination":"https://yourbrand.com/pricing","tags":["email"]}'A successful response might look like this:
txtHTTP/1.1 201 Created
Location: /v1/links/abc123
ETag: "v1"
Cache-Control: no-store
Content-Type: application/json
{"id":"abc123","slug":"spring-sale","destination":"https://yourbrand.com/pricing","created_at":"2026-03-14T09:21:07Z"}Content-Type tells the server to parse the body as JSON. A server that rejects the supplied media type can return 415 Unsupported Media Type. The idempotency key lets the client identify a retry of the same create operation. If the request times out after the server creates the link, retry with the same key rather than generating a new one.
The response gives the client what it needs to continue: 201 Created confirms creation, Location identifies the resource, and ETag marks its current version. The id, abc123, is an opaque identifier. Store it and pass it back unchanged.
| Method | Request | Success status | What it does |
|---|---|---|---|
| GET | GET /v1/links | 200 OK | Lists links with pagination and filters |
| GET | GET /v1/links/abc123 | 200 OK | Returns one link by ID |
| POST | POST /v1/links | 201 Created | Creates a link and returns a Location header |
| PUT | PUT /v1/links/abc123 | 200 OK | Replaces the full link record |
| PATCH | PATCH /v1/links/abc123 | 200 OK | Updates only the fields sent in the body |
| DELETE | DELETE /v1/links/abc123 | 204 No Content | Removes the link with no response body |
Keep the resource in the URI and use the method to express the operation. PATCH /v1/links/abc123 makes the partial update explicit, unlike a custom action such as POST /v1/links/abc123/updateDestination. HTTP methods and status codes have defined semantics in RFC 9110[5].
The update path with a version check#
Use the ETag from the create response as a precondition on the update:
bashcurl -X PATCH https://api.example.com/v1/links/abc123 \
-H "Authorization: Bearer $API_TOKEN" \
-H "Content-Type: application/json" \
-H "If-Match: \"v1\"" \
-d '{"destination":"https://yourbrand.com/spring-pricing"}'txtHTTP/1.1 200 OK
ETag: "v2"
Content-Type: application/json
{"id":"abc123","slug":"spring-sale","destination":"https://yourbrand.com/spring-pricing"}The server returns a new ETag after the update. If another edit has already changed the resource, the old "v1" precondition should fail with 412 Precondition Failed rather than overwrite that change. For field types and requirements, the developer reference for grant matching[6] provides a separate example of structured API documentation.
Retry behavior depends on the operation. GET, PUT, and DELETE are idempotent by definition, so repeating the same request has the same intended effect. A POST can create another resource if repeated, so use the same idempotency key when retrying after a timeout.
How Authentication Works in the Example#
Strip the mystique from the header and there's almost nothing there:
txtAuthorization: Bearer 9f2c41ab7d8e4c0f9b3aThree parts, in order: the scheme (Bearer, case-insensitive by spec but always written that way), exactly one space, then the raw token. No quotes around it, no token= prefix, no trailing space picked up from a copy-paste. A stray space is one of the most common reasons a token that "definitely works" returns 401.
HTTPS is not optional here. A bearer token is replayable by design: whoever captures the header string can call the API as you until that token expires. Send it over plain HTTP through a corporate proxy that logs headers and you've effectively published it.
Where the token comes from and what it can reach#
Tokens are created in a dashboard or through an API call, given a name that identifies the integration using them, and scoped to a single workspace. In RedirHub, an API token is scoped to one workspace and created in the dashboard, and it acts with the role of the person who created it. That second detail surprises people: a token minted by a workspace owner does not behave like a restricted integration credential, while a Viewer's token can only read.
Each RedirHub token gets its expiry when it is created: 30, 60, 90 or 180 days, a year, or none. A token that never expires is flagged in the token list, and a token is shown in full only once, so a lost one is replaced and revoked rather than recovered.
The failure codes split cleanly, and conflating them costs hours of debugging. 401 Unauthorized means the credentials are missing, malformed, expired or revoked, and RFC 9110 says the response should carry WWW-Authenticate: Bearer to say so. 403 Forbidden means the token is perfectly valid but the role behind it can't perform that action, such as a read-only token calling DELETE. Retrying a 401 with the same token is pointless; retrying a 403 with the same token is worse, because it suggests you think the permission problem will resolve itself.
What RedirHub's API returns for a bad token#
On 18 November 2026 we called GET https://api.redirhub.com/v1/test with curl from a cloud server in Iowa, US: five times with no Authorization header and once with an invalid bearer token. All six calls returned 401 with Content-Type: application/json and the body below, and none carried a WWW-Authenticate header. So against this API, branch on the 401 status and the message, not on the header; RFC 9110 says a 401 should carry one, but a client that waits for it will not see it here.
txtHTTP/2 401
content-type: application/json
{"message":"Unauthenticated."}The RedirHub API authentication documentation shows the header format and the token scoping rules in one page. If your API issues signed, self-contained tokens instead of opaque ones, the Visbanking JWT security walkthrough[7] covers signature validation and claim checks, which is the equivalent work on the server side.
Two habits pay for themselves. First, verify a new token with one cheap authenticated read before wiring it into anything with write access, since a token that can list but not create fails at the least useful moment otherwise. Second, put an expiry date on it. Rotating somewhere in the 30 to 90 day window keeps exposure short without turning rotation into a weekly chore.
Path, Query and Body Parameters#
Parameters live in three places, and mixing them up is how APIs end up with GET /v1/links?id=abc123 when GET /v1/links/abc123 was the obvious call. Path parameters identify. Query parameters shape a read without changing what's stored. Body parameters carry the write.
Path is the resource itself. /v1/links/{id} takes the opaque abc123 string returned in the 201 response body. It's a string, not an ordinal, and hard-coding a pattern from it breaks the day the format changes.
Query belongs on the collection endpoint and never mutates anything. ?limit=50 caps page size, cursor=eyJvZmZzZXQiOjUwfQ fetches the next page, status=active filters, and sort=-created_at orders newest first. Two rules keep cursor pagination honest: URL-encode every value, and pass the cursor back byte for byte on the next call. Decoding it to "clean it up" is how you get a page that restarts from the top.
Body carries JSON for POST and PATCH, and the Content-Type: application/json header is what makes the server attempt to parse it at all. destination is required and must be an absolute HTTPS URL. slug is required on create, unique within the workspace, lowercase and hyphenated. tags is an optional array. On PATCH, send only the fields you're changing; sending the full object with PATCH is a habit borrowed from PUT and it makes lost-update bugs more likely, not less.
| Parameter | Location | Type | Required | Example |
|---|---|---|---|---|
| id | Path | String (opaque ID) | Yes for single-resource calls | abc123 |
| limit | Query | Integer 1-100 | No | 50 |
| cursor | Query | Opaque string | No | eyJvZmZzZXQiOjUwfQ |
| status | Query | Enum | No | active |
| destination | Body | HTTPS URL string | Yes on POST | https://yourbrand.com/pricing |
| slug | Body | Lowercase string, unique | Yes on POST | spring-sale |
| tags | Body | Array of strings | No | ["email","campaign"] |
Validation is not the same as parsing#
Here's the distinction clients get wrong most often. A body that isn't valid JSON never reaches your validation logic, so it comes back as 400 Bad Request. A body that parses perfectly but sets "destination":"http://yourbrand.com/pricing" is a different failure: the syntax was fine, the data wasn't. That's 422 Unprocessable Content, and the response body names the offending field so the client doesn't have to guess.
The same split applies to slug. Sending an uppercase slug with spaces fails validation with 422. Sending a well-formed slug that already exists collides with current state, which is 409 Conflict. Field-level detail in the error body is what makes both fixable without reading server logs.
Status Codes and Problem Details Errors#
Status codes aren't decoration; they're the contract that caches, gateways, monitoring dashboards and client SDKs all branch on without parsing a byte of your JSON. RFC 9110 defines a status as a three-digit integer, with valid codes spanning 100 through 599, grouped into 2xx success, 4xx client fault and 5xx server fault (RFC 9110).
| Status | Meaning | When it appears in the example | Client action |
|---|---|---|---|
| 200 OK | Request succeeded with a body | GET returns the link or list | Read and use the JSON body |
| 201 Created | A new resource exists | POST /v1/links succeeds | Store the Location header URL |
| 204 No Content | Success with no body | DELETE /v1/links/abc123 succeeds | Treat as success; nothing to parse |
| 400 Bad Request | Malformed request syntax | JSON body fails to parse | Fix the request before retrying |
| 401 Unauthorized | Missing, invalid or expired credentials | Authorization header absent or token expired | Obtain or refresh the token |
| 403 Forbidden | Valid credentials, insufficient role | Token cannot delete or publish | Do not retry with the same token |
| 404 Not Found | Resource does not exist or is not visible | Unknown or other-tenant link ID | Check the ID; treat as permanent |
| 409 Conflict | State collision | Slug already exists | Change the slug or use If-Match |
| 422 Unprocessable Content | Valid syntax, invalid data | Destination is not HTTPS | Fix the fields named in the error body |
| 429 Too Many Requests | Rate limit exceeded | Too many writes in a window | Back off using Retry-After |
| 500 Internal Server Error | Unexpected server failure | Server-side exception | Retry with exponential backoff and report the correlation ID |
A few entries deserve a sentence each. 201 belongs only to creation, and it should always carry Location. 204 is the correct answer to a successful DELETE, and clients that try to parse a body from it will throw. 405 Method Not Allowed is what you return for a verb outside your explicit allowlist, and OWASP recommends allowlisting methods rather than relying on implicit rejection, which shrinks the verb-tampering surface. An unrecognized or unimplemented method should generally return 501, per the same RFC.
The error body clients can actually branch on#
Status codes tell a client what category of thing went wrong. They don't tell it which field, or which of three possible 422s fired. That's the job of RFC 9457 Problem Details, which standardizes the failure payload instead of letting every endpoint invent its own shape (RFC 9457[8]):
txtHTTP/1.1 422 Unprocessable Content
Content-Type: application/problem+json
{"type":"https://api.example.com/problems/invalid-destination",
"title":"Invalid destination",
"status":422,
"detail":"The destination must use HTTPS",
"instance":"/v1/links"}Decode each member once and you'll never misread one again. type is the stable, versioned identifier, and it's what client code should switch on. title is fixed human-readable text that never varies between occurrences. detail is per-occurrence display text for a human reading a log. instance echoes the request path, which pairs well with a correlation ID returned in a response header. And the JSON status member must match the actual HTTP status, because the transport status stays authoritative even when the body disagrees.
Two implementation notes that save future pain. Keep a versioned problem-type catalog so invalid-destination means the same thing forever, and return field-level metadata on 422 so a form can highlight the exact input rather than showing a toast. The RedirHub API error reference is the same idea applied to a live contract: status codes, error shapes and the fields each one returns, so client branching logic can be written against documented values instead of guesses.
Retries, Idempotency and Safe Updates#
The scenario every tutorial skips: your job sends POST /v1/links, the server commits the row, and the response is lost somewhere between the load balancer and your client. Your HTTP library raises a timeout. The work was done. You have no way to know that from the outside.
Retry blindly and you get a duplicate. Never retry and you get a link that exists but isn't recorded in your system, which is worse because it fails in a different direction.

The rule set is smaller than it feels. GET, HEAD, PUT and DELETE are expected to be idempotent, meaning a repeated identical request produces the same intended server effect as a single one; logging and metrics may still move, and that's fine. POST is not idempotent by default, and replaying it can create duplicate orders, payments or redirect rules unless the API defines an idempotency contract (HTTP methods and status codes in practice[9]).
| Method | Idempotent | Safe to retry after timeout | Protection needed |
|---|---|---|---|
| GET | Yes | Yes | Caching headers such as Cache-Control |
| HEAD | Yes | Yes | None |
| PUT | Yes | Yes | If-Match to prevent lost updates |
| DELETE | Yes | Yes | None required |
| PATCH | Depends on the patch operations | Only with absolute operations | If-Match and explicit operations |
| POST | No | Only with Idempotency-Key | Idempotency-Key header |
How Idempotency-Key actually works#
The client generates a value once, before the first attempt, and reuses it verbatim on every retry of that logical operation. The server records the key alongside the response it produced. When the same key arrives again, the server doesn't create anything; it replays the stored outcome, including the original 201 and the original Location header.
That replay behavior matters for client code. A retried POST that comes back 201 is not a new resource; it's the first one, handed back a second time. Don't log it as a creation and don't fire a "link created" webhook from the client side. Generate a fresh key per logical operation (a UUID v4 is fine), store it with the request record, and never reuse a key for a different payload.
Lost updates and stale representations#
The second concurrency problem is two people editing the same link. The GET response returns ETag: "v3". Both editors receive it. The first sends If-Match: "v3" with their PATCH and gets 200 with a new ETag. The second sends If-Match: "v3" and gets 412 Precondition Failed, which is the API doing them a favor: without the precondition, their write would have overwritten a change they never saw.
Put that header on every edit call your integration makes. It's one line of code and it converts a silent data loss into a visible conflict a human can resolve.
Finally, caching. Cache-Control: max-age=60 on a read-heavy list endpoint takes real load off the origin, and no-store on a freshly created workspace-private record keeps it out of shared caches. For teams running redirects, links or infrastructure through an API, this whole set is the difference between a migration that publishes cleanly and one that half-applies, overwrites a live destination, or creates the same mapping twice under load.
Authorization Checks Beyond the Token#
Here's the claim worth arguing about: a technically correct REST API example can still be unsafe, because validating a token and authorizing an action are different operations and only the first one appears in most tutorials. You can accept a perfectly signed credential and still let its holder delete a stranger's link.
The scale of that gap isn't theoretical. Akamai's 2026 State of the Internet report on apps, APIs and DDoS found that 87% of organizations had at least one API security incident in 2025, with broken authentication and broken authorization among the most common causes[10].

The one negative test every team should run#
Take a valid token belonging to tenant A. Call GET /v1/links/{id} with an ID owned by tenant B. The only acceptable answers are 404 Not Found, if the API prefers not to confirm the record exists, or 403 Forbidden if it does. Returning the record, or returning a 200 with an empty body where a 404 belongs, is a cross-tenant data leak that no amount of correct REST verb usage redeems.
Run the write version too. DELETE /v1/links/{id} across tenants, PATCH against another workspace's slug, and POST with a tags value that references someone else's campaign ID. Then run the workflow version: a read-only marketing token attempting to publish a redirect, or a Terraform integration token attempting to change billing settings. A token that's valid, unexpired and correctly scoped for reads should still be stopped at the publish step.
The checks to build, in the order they'll bite you:
- Object-level ownership on every read and every write, resolved from the token's workspace, not from a client-supplied header.
- Role-based permissions evaluated after token validation and before any database mutation.
- Least-privilege scopes so an automation that only creates links can't also delete domains.
- Per-token rate limits, which cap the damage a leaked credential can do in the window before you rotate it.
- Audit events on every mutation, recording which token acted, from which workspace and against which resource.
That last one is where a link-management platform earns trust. On RedirHub Pro, every link's change history shows who changed it, when, the old and new values, and where the change came from (Dashboard, API, MCP, CSV import or Auto-redirect), so an unexpected edit can be traced to the integration that made it rather than to "someone".
The habit that holds all of it together is automated negative testing. Encode the cross-tenant attempts as integration tests that run in CI on every pull request. A refactor that removes an ownership check in a controller will pass review, pass the happy-path tests, and open a cross-tenant read path unless something fails loudly. Authorization regressions are invisible in normal traffic by design, which is exactly why they need a test that fails on purpose.
Run the Example End to End#
A request can pass authentication and still fail at validation, conflict with an existing resource, or target the wrong workspace. Run the example in sequence so each response tells you what to check next.

- Create a workspace-scoped token. Create it in the RedirHub dashboard and store it in a server-side secrets manager. The token acts with the role of the person who created it, so it can do whatever that role allows in the workspace; never put it in a browser bundle.
- Verify the token. Call
GET /testwith the bearer token. A successful response confirms that the token works without creating or changing a link. - Set the base URL. Replace
https://api.example.com/v1withhttps://api.redirhub.com/v1. The RedirHub API uses one bearer token and JSON, with an OpenAPI 3.1.0 specification that covered 30 operations across 22 paths as of 18 November 2026. - Read before writing. Make a read request and check the status and JSON response. A 401 points to an authentication problem; a successful response confirms the request reached the API.
- Create once. Send the
spring-saleexample as aPOSTrequest. Check the documented response and save the returned resource identifier before deciding whether to retry. - Handle a timeout carefully. The server may have created the resource even if the client never received the response. Do not assume a repeated
POSTis safe: use an idempotency key only if the endpoint documents support for it, or read the collection and check for the resource before sending another create request. - Exercise error handling. Send a malformed request and a request for a resource that does not exist. Check the actual status codes and error bodies returned by the API; do not assume every endpoint uses
application/problem+json. - Test the workspace boundary. Use a token from a different workspace and confirm it cannot read or change the first workspace's resources. A valid token is not permission to cross workspace boundaries.
- Update deliberately. Before editing a resource, check the endpoint's documented update and concurrency behavior. Send conditional headers such as
If-Matchonly when the endpoint supports them.
For larger changes, the RedirHub bulk redirect API guide covers bulk import, export, update and delete, with a preview before changes are written.
Use the same sequence in an integration test: verify the token, read a resource, make one controlled change, and check the result before retrying.
Manage redirects and short links through an API
The RedirHub Management API is on every plan: one bearer token per workspace, JSON in and out, and redirects and branded short links on your own domains.
Read the API docsSources
- [1]Gartner, Hype Cycle for APIs, 2024
- [2]Roy Fielding, Architectural Styles and the Design of Network-based Software Architectures (2000), Conclusions
- [3]SANS 2024 Application Security & API Survey: Protecting our Applications and APIs
- [4]REST API | StalkChain Docs
- [5]RFC 9110: HTTP Semantics
- [6]Grantlas API reference
- [7]How to Secure REST API with JWT for Banking (Visbanking)
- [8]RFC 9457: Problem Details for HTTP APIs
- [9]HTTP Methods and Status Codes: The Full Picture (BoringDocs)
- [10]Akamai, State of the Internet 2026: Apps, APIs and DDoS
Frequently asked questions
A REST API example shows one complete call: the method, URL, headers and body a client sends, and the status code, headers and JSON the server returns. A useful one also shows the failure cases, such as 401, 422 and 409, so you can write the error handling as well as the happy path.
401 Unauthorized means the credentials are missing, malformed, expired or revoked, so the fix is a valid token. 403 Forbidden means the token is valid but its role cannot perform that action, so retrying with the same token will not help.
Not by default. The server may have created the resource before the response was lost, so a blind retry can create a duplicate. Retry with the same Idempotency-Key if the API supports one, or list the collection first and check whether the resource already exists.
Return 400 Bad Request when the request cannot be parsed, such as invalid JSON. Return 422 Unprocessable Content when the body parses but the data breaks a rule, such as a destination that is not HTTPS, and name the failing field in the error body.
Create an API token in the RedirHub dashboard and send it on every request as Authorization: Bearer followed by the token. Each token works for one workspace and acts with the role of the person who created it, and GET /test checks that a token is live.

Leo Astarothman is the Brand & Content Lead at RedirHub, where he shapes the company's visual identity, educational content, product experiences, and marketing strategies. He also specializes in system design. Simplifying complex redirect infrastructure into practical resources, product experiences, and campaigns that help businesses understand and adopt modern redirect management.
Related Articles
View All Articles


