What Is an API? How Web Services Connect (REST, Endpoints, Auth)

An API (Application Programming Interface) is an agreed contract for calling one piece of software's functionality from another program. Among these, the Web API — called over the network with HTTP — is the foundation of nearly every service integration you meet: maps, payments, weather, generative AI. This article walks through endpoints and HTTP methods, what requests and responses actually contain, the ideas behind REST, authentication and authorization, and the real-world pitfalls such as CORS and rate limits.

The bottom line first: understanding a Web API means being able to read four things — which URL, with which method, what you send, and what comes back. Add authentication (who you are calling as) and error handling (what to do when it fails), and you can read almost any API documentation on your own.

1. What an API is — a contract for use

An API is a specification of a doorway: the provider promises "call it in this format, and I will answer in this format." The classic analogy is a restaurant menu. The customer (the caller) does not need to know how the kitchen works; ordering by the name on the menu is enough to get the dish. Being usable without knowing the implementation is the essence of an API.

Keeping that promise is the provider's responsibility, which is exactly why APIs carry a version (/v1/ and so on). When a change would break the promise, the convention is to publish it as a new version instead.

2. Endpoints and HTTP methods

The URL you call is the endpoint. The endpoint says which resource you mean, and the HTTP method says what you want to do to it.

Example: https://api.example.com/v1/users/42 points at the resource "the user whose ID is 42."

MethodMeaningProperties
GETRetrieve (GET /v1/users/42)Safe (does not change server state) and idempotent
POSTCreate (POST /v1/users)Not idempotent (sending twice may create two)
PUTReplace as a whole (PUT /v1/users/42)Idempotent (same result however many times you send it)
PATCHUpdate part of a resourceNot necessarily idempotent; depends on the implementation
DELETEDelete (DELETE /v1/users/42)Idempotent (no further change once it is gone)

Idempotent means "sending the same request any number of times leaves the state the same." It decides whether a request can be safely retried after a network error, which makes it a practically important distinction. Because POST is not idempotent, payment-like operations commonly attach an idempotency key (an Idempotency-Key header, for example) to prevent double execution.

Filters and options are passed in the query string: GET /v1/users?role=admin&limit=20. Values containing spaces, symbols or non-ASCII characters must be URL-encoded.

3. What requests and responses contain

An HTTP exchange splits into headers (metadata) and a body (the data itself). Web APIs conventionally carry JSON in the body.

POST /v1/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOi...
Accept: application/json

{"name": "Taro Tanaka", "role": "admin"}

The answer comes back as a status code, headers, and a JSON body.

HTTP/1.1 201 Created
Content-Type: application/json

{"id": 42, "name": "Taro Tanaka", "role": "admin"}

The status code — three digits saying what happened — is the key to reading any API.

CodeMeaningTypical situation
200 OKSuccessA GET returned data
201 CreatedCreated successfullyA POST created a resource
204 No ContentSuccess, no bodyA DELETE completed
400 Bad RequestMalformed requestA required field is missing; the JSON is broken
401 UnauthorizedNot authenticatedNo token, or the token expired
403 ForbiddenNot permittedAuthenticated, but not allowed to do this
404 Not FoundNo such resourceYou asked for an ID that does not exist
429 Too Many RequestsCalled too oftenYou hit the rate limit
500 Internal Server ErrorServer-side failureA bug on the API provider's side
Telling 4xx from 5xx is the first step. A 4xx is your problem (the caller's), so fix what you are sending. A 5xx is their problem (the server's), and changing your input will not fix it — wait, retry, and contact the provider if it persists. Making this one distinction first eliminates a great deal of wasted debugging.

4. The ideas behind REST — resources and statelessness

REST (Representational State Transfer) is an architectural style presented by Roy Fielding in his 2000 doctoral dissertation. It is neither a protocol nor a standard, but a set of principles for "building the way the Web works," and an API that follows them is called RESTful.

REST's advantage is that it reuses what HTTP already gives you — methods, status codes, caching. The learning curve is gentle and it plays well with tooling, proxies and CDNs, which is why it became the de facto standard for Web APIs.

5. Authentication and authorization — API keys, Bearer tokens, OAuth

For anything beyond public data, an API needs to know who is calling. Authentication (who you are) and authorization (what you may do) are distinct concepts.

Never put a secret key in browser JavaScript. Front-end code and network traffic are both fully visible to users. Make calls that need secret credentials from your own server, and have the browser call your server's API instead (a BFF or proxy). Keeping keys in server-side environment variables — and out of the repository — matters just as much.

6. Common pitfalls — CORS, rate limits, error handling

Once you start calling APIs for real, three walls show up almost every time.

CORS (the cross-origin restriction)

By default, browsers forbid one site's JavaScript from freely reading an API on a different origin (the combination of scheme, domain and port). To allow it, the API side must return an Access-Control-Allow-Origin header. The crucial point is that CORS is a restriction the browser imposes: it does not apply to server-to-server calls or to curl. If it "works in curl but fails in the browser," suspect CORS first.

Rate limits

Most APIs cap you at something like N calls per minute and answer with 429 Too Many Requests when you exceed it. A Retry-After header or remaining-quota headers usually come back — honour them. Retries should use exponential backoff (wait 1s, 2s, 4s…) rather than hammering the endpoint immediately.

Error handling and timeouts

Calls over a network fail as a matter of course. Always check the status code (fetch does not throw on a 404 or 500), set a timeout, and decide up front that only idempotent operations may be retried.

const res = await fetch('https://api.example.com/v1/users/42', {
  headers: { 'Authorization': 'Bearer ' + token, 'Accept': 'application/json' }
});
if (!res.ok) throw new Error('API error: ' + res.status);
const user = await res.json();

7. Alternatives to REST — GraphQL, gRPC, WebSocket

REST is not universal. Other approaches suit other needs.

StyleCharacteristicsWhere it fits
RESTURL = resource, HTTP method = action; JSON is the normGeneral-purpose Web APIs; when caching matters
GraphQLThe client specifies exactly which fields it wantsWhen each screen needs very different data
gRPCGenerated from a schema; fast binary transportInternal communication between microservices
WebSocketKeeps a connection open for two-way messagingChat, notifications — anything the server must push

When in doubt, start with REST. The learning cost is low, the tooling is mature, and you can migrate to or combine other styles later if you need to. GraphQL is worth considering once over-fetching (fields you never use) and under-fetching (calling the API repeatedly to fill one screen) actually start to hurt.

Free Tool Read API responses with the JSON Formatter Paste a one-line API response and format it in your browser to inspect its structure. Syntax errors are pinpointed too.

Frequently asked questions (FAQ)

What is the difference between an API and a Web API?

API is a broad term for any agreed contract that lets one piece of software call another's functionality; operating system calls and library functions are APIs too. A Web API is specifically one you call over the network using HTTP. When people today say they are calling an API, they usually mean a Web API that exchanges JSON.

Should I use REST or GraphQL?

It depends on the use case. If your work is mostly creating, reading, updating and deleting resources, and you want to take advantage of HTTP caching and status codes as they are, REST is the easier choice. If the fields each screen needs vary a lot and you want to fetch several resources at once (avoiding over-fetching and under-fetching), GraphQL fits better. Starting with REST and reconsidering when the need actually appears is the pragmatic path.

Is it safe to put an API key in front-end JavaScript?

Never put a secret API key in browser-side code. Both the JavaScript source and the network traffic are visible to users, so the key leaks immediately. Make calls that require a secret key from your own server, and have the browser call your server's API instead. If you truly must call directly from the browser, use a key that is designed to be public (with narrowly scoped permissions) and combine it with referrer or domain restrictions and rate limiting.

← Back to all articles