SmartKitio

Programming

What Is an API and How Does It Work?

Application Programming Interface is a broad term: any defined surface where one module calls another. In web development, the phrase usually means an HTTP API—often JSON over REST-ish routes—where a client program asks a server program to read or change shared state. Understanding that request–response lifecycle explains most integration bugs before you open a debugger.

8 min read · Updated 2026-10-04

Network cables and server hardware suggesting connected systems
Photo via Unsplash · Unsplash License

Client, server, and the contract

A client initiates work: browser JavaScript, a mobile app, a server-side cron job, or a CLI. A server listens on the network, authenticates the caller, validates input, touches databases or other services, and returns a response. The API is the written contract—URLs, methods, headers, body schemas, error shapes, rate limits—not the framework brand on either side.

Both sides may be servers in practice: your Next.js app is a client when it calls Stripe, and Stripe’s API is the contract you import from documentation. Webhooks flip direction—the payment provider becomes the client POSTing to your endpoint— but the same rules apply: verify signatures, parse JSON, return a meaningful status, and make handlers idempotent because retries are guaranteed.

Endpoints and resources

An endpoint is a method plus a path (and sometimes query rules) that performs one documented operation. RESTful designs map paths to nouns (/users/42/orders) and use HTTP methods to express intent. Not every public API is strictly REST—RPC-style paths like /createInvoice still appear—but predictable URLs and consistent JSON fields reduce client pain.

Query strings filter and paginate collections: GET /v1/articles?tag=api&page=2&limit=20 should document defaults, max limits, and sort order. Path parameters identify resources (/articles/what-is-an-api); query parameters refine the request. Mixing them inconsistently—sometimes putting an id only in the query—forces every client to special-case your API. Document which parameters are required, which are stable for caching, and which change response shape.

HTTP methods

Common HTTP methods in JSON APIs

MethodTypical intentSafe?Idempotent?
GETRead a resource or collectionYesYes
POSTCreate or non-idempotent actionNoNo
PUTReplace a resource at a URLNoYes
PATCHPartial updateNoOften
DELETERemove a resourceNoYes

Safe means the server should not change state; idempotent means repeating the request should not multiply side effects. Caching and retry logic depend on these semantics.

Headers: metadata the server reads first

  • Content-Type tells the server how to parse the body (application/json).
  • Accept asks for JSON (application/json) or other representations.
  • Authorization carries bearer tokens, API keys, or scheme-specific credentials.
  • User-Agent, X-Request-ID, and trace headers aid logging and support.

Body and JSON payloads

GET requests usually have no body; POST and PATCH often send JSON documents. Servers validate required fields, types, and business rules before writing to a database. Clients should send UTF-8 JSON with correct Content-Type and pretty-print only in dev—whitespace does not change meaning but wastes bytes. Before you paste a failing payload into a ticket, run it through a formatter: a missing comma or a smart quote from a spreadsheet looks like a server bug until the JSON is valid.

One call: request and response

HTTP is text-first on the wire: a request line, headers, a blank line, then an optional body; the server answers with a status line, headers, blank line, and optional body. JSON APIs keep both sides machine-readable. The request below creates an article; the response returns the stored record with server-assigned fields.

http
POST /v1/articles HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOi…
Accept: application/json
Content-Length: 89

{
  "title": "What Is an API?",
  "slug": "what-is-an-api",
  "published": true
}
http
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: /v1/articles/art_7k2m
Cache-Control: private, max-age=0

{
  "id": "art_7k2m",
  "slug": "what-is-an-api",
  "title": "What Is an API and How Does It Work?",
  "published": true,
  "created": "2026-10-04T14:22:00Z",
  "updated": "2026-10-04T14:22:00Z"
}

Notice how the response echoes client fields but adds id and timestamps the client did not send. A follow-up GET /v1/articles/what-is-an-api might return 200 with the same JSON shape; PATCH might send only { "published": false } and answer 200 with the updated document. SmartKitio’s json-formatter helps you compare those bodies side by side—field names, nesting, and trailing commas show up immediately when two environments disagree.

Status codes summarize outcomes

HTTP status codes are three-digit summaries: 2xx success, 3xx redirection, 4xx client mistake, 5xx server failure. APIs still return JSON error bodies with machine-readable codes, but the status tells intermediaries and generic clients how to retry or cache. When a gateway returns 502 Bad Gateway, the problem may be upstream; when your app returns 422, the JSON likely reached the handler but failed validation—http-status-lookup clarifies the category while you read the body.

Status codes you will see in JSON APIs

CodeMeaningTypical client action
200 OKSuccess with a bodyParse JSON; update UI
201 CreatedResource createdRead body; follow Location if present
204 No ContentSuccess, empty bodySkip JSON.parse; treat as done
400 Bad RequestMalformed JSON or bad syntaxFix payload; do not retry unchanged
401 UnauthorizedMissing or bad authRefresh token or re-login
403 ForbiddenAuth ok, permission deniedShow error; do not retry as same user
404 Not FoundNo resource at pathCheck URL; may be intentional hide
409 ConflictDuplicate or version clashMerge, refetch, or ask user
422 UnprocessableSchema ok, rules failedShow field errors from body
429 Too Many RequestsRate limitedBackoff; honor Retry-After
500 Internal Server ErrorUnexpected server faultRetry with idempotency; alert ops
502 / 503Gateway or overloadRetry later; check status reference

Error handling on the client

Robust clients treat non-2xx responses as first-class outcomes, not exceptions buried in console noise. Read status, then parse JSON if Content-Type is application/json; some proxies still return HTML error pages on 502, which will throw on JSON.parse—that distinction saves hours. Stable APIs document an error envelope: a string code for programmatic branches, a human message, and optional details arrays for validation.

http
HTTP/1.1 422 Unprocessable Content
Content-Type: application/json

{
  "error": "validation_failed",
  "message": "Slug is already in use",
  "fields": {
    "slug": ["must be unique"]
  }
}

Authentication patterns

Bearer tokens in the Authorization header dominate mobile and SPA backends. OAuth2 and OpenID Connect delegate login to identity providers. API keys in headers are simple but leak easily from client bundles—prefer short-lived tokens and server-side exchange. Never put secrets in query strings where logs and Referer headers copy them; if a value must be in a URL, percent-encode it and treat it as public.

Request lifecycle

Typical JSON API call
  1. Client builds URL

    Path, query (encoded), optional fragment stays local

  2. DNS + TCP + TLS

    Resolve host, connect, negotiate HTTPS

  3. Send HTTP request

    Method, headers, optional JSON body

  4. Server middleware

    Auth, rate limits, logging, routing

  5. Handler + data layer

    Validate input, query database, apply rules

  6. Response

    Status, headers, JSON body or empty

  7. Client parses

    JSON.parse, handle errors, update UI

Failures can happen at every layer—TLS, auth, validation, or business logic.

When a call fails, narrow the layer before you edit code: TLS handshake errors never reach JSON parsers; 401 happens in middleware before your handler; 422 means the handler ran validation. Capture the raw request (method, URL, headers, body) and response status in one log line or HAR export, then validate the JSON locally. That workflow is why json-formatter and http-status-lookup are paired in the related tools for this article—they match how integrators actually debug.

REST and other styles (briefly)

REST uses HTTP semantics, stateless servers, and resource-oriented URLs—still the default mental model for public HTTP APIs. GraphQL sends one POST with a query document so clients fetch shaped graphs in a single round trip. gRPC uses Protocol Buffers over HTTP/2 for efficient internal microservices. Webhooks invert the flow: the server POSTs to your URL when events happen. Pick based on clients, latency, and tooling—not fashion.

Reading a successful GET

http
GET /v1/articles/what-is-an-api HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer eyJhbGciOi…
http
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Cache-Control: private, max-age=60
ETag: "art_7k2m-v3"

{
  "id": "art_7k2m",
  "slug": "what-is-an-api",
  "title": "What Is an API and How Does It Work?",
  "updated": "2026-10-04"
}

Versioning and stability

Public APIs outlive individual apps. Versioning tells clients which contract they are speaking without freezing every field forever. The most visible pattern is a path prefix (/v1/, /v2/) so entire route trees can diverge. Header versioning (Accept: application/vnd.company.v2+json) keeps URLs stable but demands disciplined clients. Query parameters (?api-version=2) appear in logs and caches—use them only when you accept that visibility.

  • Document stable error JSON: code, message, optional field-level details.
  • Prefer additive changes: new optional fields and new endpoints break fewer clients than renames.
  • Deprecate with Sunset headers or documented cutoff dates; keep v1 read-only before removal.
  • Idempotency-Key headers on POST help safe retries for payments and creates.
  • Publish OpenAPI or JSON Schema so json-formatter paste jobs can be checked against the same shapes your server validates.

When an integration breaks, compare the failing request to the contract: method, path, Content-Type, auth header, and exact JSON keys. Paste request and response bodies into json-formatter to spot a camelCase mismatch or an extra string where the schema expects a number; pair that with http-status-lookup when the status alone does not explain whether to fix the client, the server, or the proxy in between.

What to remember

  • An API is the contract—URLs, methods, headers, bodies, errors—not the framework logo on the repo.
  • Always read status first, then parse JSON; not every error body is JSON.
  • Encode and decode URLs at component boundaries; secrets belong in headers, not query strings.
  • Version explicitly; additive evolution beats silent breaking changes.

SmartKitio’s json-formatter and http-status-lookup are built for the debugging loop this article describes: validate and pretty-print payloads locally, then look up the status code your client or curl received. Use them together with the url-encoder when query parameters are part of the failing request.

References

  1. RFC 9110 — HTTP Semantics
  2. MDN — An overview of HTTP
  3. OpenAPI Specification

Related articles