How REST APIs Work and How to Call One in Practice

A walkthrough of REST's core rules, ending in real curl calls.

Cover illustration for “How REST APIs Work and How to Call One in Practice”

REST APIs become easier to understand when you treat them as a predictable exchange. This guide explains the mechanics, then puts them to work with curl. The central idea is simple. Each request has its own context, names a resource, and asks for an operation. The response tells you what happened.

What REST actually is — and what it is not

REST is an architectural style. It can run on HTTP without being HTTP itself. The distinction is between a design and its transport. REST sets constraints on how systems talk to each other, while HTTP has the methods, headers, and status codes they use to do so. Confusing them is like confusing the rules of the road with the delivery van.

Three roles make the design concrete. The client initiates a request, the server hosts resources, and the resource is the data or functionality being accessed. Each resource has a unique URL and is operated on through standard HTTP methods. REST defines six constraints, including stateless communication, a uniform interface, client-server separation, cacheability, a layered system, and optional code on demand. The uniform interface lets a Python client and a JavaScript client call the same endpoint the same way, without requiring either to speak the server’s programming language.

Why statelessness is the constraint that shapes everything else

Statelessness means each request must contain everything the server needs to handle it. A server can keep a stored prompt template without remembering the caller’s last request. The distinction is small but essential.

Because each request stands on its own, horizontal scaling, fault tolerance, and load balancing are easier. Any server instance can handle a request without needing to share session state from an earlier call. Requests do not need a particular server’s recollection. For callers, the price is repetition, because authentication credentials, context, and parameters must be supplied with every call. The protocol still requires those details on later calls, even after the caller has logged in.

The same rule explains the shape of stateless LLM inference calls. The request must have the context needed for that inference, without relying on the server to remember an earlier prompt. Full context can make requests larger. In most architectures, that cost is acceptable because independent requests are easier to distribute across servers. The server’s lack of conversational memory is a design choice.

The five HTTP methods and what they actually do to a resource

The uniform interface works through five HTTP methods. GET retrieves a resource without modifying it and is safe and idempotent, meaning repetition does not add changes. POST creates a resource, so sending the same request twice can create two resources. PUT replaces the whole resource, so fields left out are treated as absent. PATCH updates only the fields supplied. DELETE removes a resource.

These operations map to CRUD, meaning Create, Read, Update, and Delete. The method is part of the contract. Choosing the wrong one is an API design error. In AI APIs, POST can submit an inference request, GET can retrieve model metadata or prior run results, PUT can replace a stored prompt template, and DELETE can remove an artifact. The POST distinction becomes especially important during retries, because “try again” can mean “create another.”

How the request is built — endpoint, headers, parameters, and body

Once the method establishes the operation, four components describe its target and inputs. The endpoint is the URL identifying the resource being accessed. Headers supply metadata, including authentication credentials and content type. Parameters identify a particular resource or refine the requested results. The body supplies data for creation or updates.

Path and query parameters serve different purposes. A path parameter names a resource by ID, while query parameters can filter, sort, or paginate the results and leave the resource path as it is. The path answers which resource is involved. Query parameters narrow or arrange what comes back, so they are not interchangeable with the address itself. Reading an API reference becomes easier when those roles remain separate.

POST, PUT, and PATCH requests send the data to be created or changed in their bodies, most often as JSON. An LLM inference request brings the pieces together. Its endpoint identifies the model, its Authorization header supplies a bearer token, and its body contains the model name, a messages array, and optional parameters such as temperature. The token identifies the caller. The JSON body is the payload the server processes before returning its response.

How the server responds — status codes as the primary signal

The HTTP status code is the primary machine-readable signal of the outcome. The body has more detail, but client code should use the status to choose a branch. A POST that creates a resource returns 201 Created and should include a Location header pointing to it. A successful DELETE commonly returns 204 No Content.

Client errors distinguish different kinds of failure. A 400 Bad Request means the server cannot or will not process the request because of a client error, such as malformed syntax or invalid message framing. A 401 Unauthorized asks, in effect, “Who are you?” A 403 Forbidden means the authenticated caller does not have permission, while 422 Unprocessable Entity means the request is well-formed but does not pass validation. A 429 Too Many Requests means a rate limit has been exceeded and the caller should back off.

Those distinctions disappear when an API returns 200 OK with an error body such as {"status": "error", "code": "not_found"}. Every consumer must then read the body just to find out if the request worked. The status says success while the payload disagrees. Response headers also provide caching directives, giving REST a structural advantage through standard HTTP caching. GraphQL and gRPC require significant additional work to match that capability.

Making your first REST API call with curl

To put the mechanics into practice, start with an authenticated GET before attempting a write. Home Assistant has a REST API at http://<host>:8123/api/ that uses bearer-token authentication. A minimal curl header is curl -H "Authorization: Bearer $TOKEN", with the target URL added to complete the command. The -H flag appends a header. Here, $TOKEN references an environment variable rather than spelling out the credential in the saved command.

For a real request, replace <host> with the Home Assistant host and use the documented endpoint for retrieving all entity states. The command structure is curl -H "Authorization: Bearer $TOKEN" "<entity-states-endpoint>", where the final placeholder must be replaced with that endpoint’s full URL. The placeholder is not a working address.

That GET returns a JSON array of entity-state objects. Each object includes entity_id, state, attributes, the timestamps last_changed, last_reported, and last_updated, plus a context object. The array is the representation of the requested data. Reading it connects the earlier abstractions to a visible result, with the client sending credentials and a resource address and the server returning structured information.

Next comes a POST to trigger a service action. Its command begins curl -X POST -H "Authorization: Bearer $TOKEN", followed by the documented service-action endpoint and any body that action requires. The -X POST portion selects the method. Unlike the GET, this request asks the server to do something, so the action and its required inputs must come from the API documentation.

Bearer tokens are not the only authentication pattern curl supports. APIs may instead take an API key in an X-API-Key header or use username-and-password authentication with curl’s -u option. The API determines which pattern is valid. When debugging any of them, log the raw HTTP response, including its status code and headers.

Keeping credentials out of your code and command history

Once a call works, avoid the easy shortcut of pasting its token into code. That shortcut turns a successful experiment into a credential-exposure risk. Credentials must stay out of source code and configuration files that are committed, URLs, and shell commands saved to history. URLs are especially unsuitable because they appear in server logs and browser history. A secret is still a secret when it sits next to a setting.

For local work, load credentials through environment variables, using a .env file that .gitignore keeps out of version control. For production systems, use a secrets manager or vault in place of environment variables loaded from flat files. The rule is short enough to remember. Keep secrets separate from the code and commands that use them.

Where REST fits in architectures that also use GraphQL and gRPC

REST, GraphQL, and gRPC need not compete for the entire architecture. Production systems often use all three at different layers, each where its strengths fit the needs of those who use it. REST works with browsers, curl, and low-code tools without the need for special client libraries. Its learning curve is lower and its tooling support wider. Combined with the HTTP caching already described, those qualities make it a strong fit for public APIs.

REST’s fixed routes can still return more or fewer fields than a client needs. That is the over-fetching and under-fetching problem GraphQL was designed to solve. A frontend team may therefore prefer GraphQL when shaping responses is central to its work. The choice follows the consumer’s needs.

For high-volume internal microservice communication, gRPC offers higher raw throughput through binary Protobuf serialization than through verbose JSON. That makes it a natural fit for service-to-service traffic at scale. It solves a different problem from public accessibility. Choose according to who will consume the API, with external developers favoring REST, a frontend team potentially favoring GraphQL, and internal services at scale favoring gRPC. An architecture can split the work this way without naming a winner and holding a small awards ceremony.

How AI agents are changing the way REST APIs are consumed

AI agents change the demands on this interface more than its basic mechanics. They call faster, retry more aggressively, and need to discover available operations at runtime rather than rely on a developer who has already read the documentation. Most AI REST APIs are at Level 2 of the Richardson Maturity Model, where they use HTTP verbs and status codes without hypermedia navigation. Those conventions explain operations and outcomes. They do not, by themselves, give an agent a discoverable description of what an endpoint can do.

MCP, or Model Context Protocol, helps agents find what endpoints can do by wrapping REST endpoints that already exist with tool schemas and natural language descriptions. Agents can find and query those descriptions at runtime without anyone having to rewrite the API underneath. The wrapper adds a new way to consume the interface. Gartner’s 2026 forecast put MCP support at 75% of API gateways by the end of 2026. That is a forecast of broader access to existing capabilities, with HTTP fundamentals remaining essential.

Agent traffic also makes retry handling and rate limits more consequential. For teams serving agents, the recommended practices are idempotency keys in request headers, stored server-side, for POST and PATCH endpoints, and separate rate-limit tiers for agent clients. Without idempotency, retries after network failure can trigger duplicate writes or charges. Human-paced limits do not fit agent-paced traffic. The caller may now be an agent, but safe consumption still depends on understanding the request, the operation it asks for, and the status the server returns.

Sources

  1. REST API for AI Models Explained: 2026 Guide

    Supplied the AI-model API examples: stateless LLM inference calls, Richardson Level 2, MCP wrapping, and agent-oriented retry and rate-limit practices.

  2. REST APIs: How They Work and What You Need to Know

    Covered the basics of client, server and resource roles and how REST uses standard HTTP methods.

  3. What is RESTful API? - RESTful API Explained - AWS

    Backed the REST constraints, including statelessness, uniform interface, cacheability, layered system and code on demand.

  4. What Is a REST API? Examples, Uses, and Challenges

    Illustrated how HTTP methods map to CRUD operations and how REST requests and responses look in practice.

  5. REST Architecture

    Explained REST as an architectural style distinct from HTTP and the statelessness constraint.

  6. Understanding Idempotency in APIs: Why It Matters and How DreamFactory Supports It

    Informed the discussion of idempotency, safe methods and why retries on POST can cause duplicate writes.

  7. What Are the Components of an API?

    Supported the breakdown of a request into endpoint, headers, parameters and body.

  8. What is an API Endpoint? Understanding API URLs and Routes

    Informed the explanation of endpoints and the difference between path and query parameters.

AllAboutAPIs Editors