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

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
| Method | Typical intent | Safe? | Idempotent? |
|---|---|---|---|
| GET | Read a resource or collection | Yes | Yes |
| POST | Create or non-idempotent action | No | No |
| PUT | Replace a resource at a URL | No | Yes |
| PATCH | Partial update | No | Often |
| DELETE | Remove a resource | No | Yes |
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.
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/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
| Code | Meaning | Typical client action |
|---|---|---|
| 200 OK | Success with a body | Parse JSON; update UI |
| 201 Created | Resource created | Read body; follow Location if present |
| 204 No Content | Success, empty body | Skip JSON.parse; treat as done |
| 400 Bad Request | Malformed JSON or bad syntax | Fix payload; do not retry unchanged |
| 401 Unauthorized | Missing or bad auth | Refresh token or re-login |
| 403 Forbidden | Auth ok, permission denied | Show error; do not retry as same user |
| 404 Not Found | No resource at path | Check URL; may be intentional hide |
| 409 Conflict | Duplicate or version clash | Merge, refetch, or ask user |
| 422 Unprocessable | Schema ok, rules failed | Show field errors from body |
| 429 Too Many Requests | Rate limited | Backoff; honor Retry-After |
| 500 Internal Server Error | Unexpected server fault | Retry with idempotency; alert ops |
| 502 / 503 | Gateway or overload | Retry 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/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
Client builds URL
Path, query (encoded), optional fragment stays local
DNS + TCP + TLS
Resolve host, connect, negotiate HTTPS
Send HTTP request
Method, headers, optional JSON body
Server middleware
Auth, rate limits, logging, routing
Handler + data layer
Validate input, query database, apply rules
Response
Status, headers, JSON body or empty
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
GET /v1/articles/what-is-an-api HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer eyJhbGciOi…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
Related articles

Technology
What Happens When You Enter a URL?
A step-by-step path from keypress to first paint, including DNS, TLS, redirects, and caching.
8 min read · 2026-10-04
Read the article
Programming
JSON Explained: Why It Became So Popular
From Douglas Crockford’s minimal syntax to the default language of web APIs—how JSON won, what it forbids, and where it still hurts.
6 min read · 2026-10-04
Read the article
Web
Client-Side vs Server-Side Processing
Where computation runs shapes privacy, latency, cost, and trust. A practical map of browser work versus server work—and what hybrid apps actually do.
5 min read · 2026-10-04
Read the article
Programming
Encoding vs Encryption: What's the Difference?
Encoding, encryption, hashing, and compression solve different problems. Confusing them—especially Base64 with secrecy—creates real security failures.
6 min read · 2026-10-04
Read the article
