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.
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.
- API: the broad term. Operating system calls and library functions are APIs too.
- Web API: the subset you call over the network with HTTP. When people say "call an API" today, they almost always mean this.
- The provider is free to rewrite its internals. As long as the promise (the interface) does not change, callers are unaffected.
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."
| Method | Meaning | Properties |
|---|---|---|
| GET | Retrieve (GET /v1/users/42) | Safe (does not change server state) and idempotent |
| POST | Create (POST /v1/users) | Not idempotent (sending twice may create two) |
| PUT | Replace as a whole (PUT /v1/users/42) | Idempotent (same result however many times you send it) |
| PATCH | Update part of a resource | Not necessarily idempotent; depends on the implementation |
| DELETE | Delete (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.
| Code | Meaning | Typical situation |
|---|---|---|
| 200 OK | Success | A GET returned data |
| 201 Created | Created successfully | A POST created a resource |
| 204 No Content | Success, no body | A DELETE completed |
| 400 Bad Request | Malformed request | A required field is missing; the JSON is broken |
| 401 Unauthorized | Not authenticated | No token, or the token expired |
| 403 Forbidden | Not permitted | Authenticated, but not allowed to do this |
| 404 Not Found | No such resource | You asked for an ID that does not exist |
| 429 Too Many Requests | Called too often | You hit the rate limit |
| 500 Internal Server Error | Server-side failure | A bug on the API provider's side |
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.
- Resource-oriented: URLs are nouns (the thing), and the action is the HTTP method. It is
DELETEon/v1/users/42, not/v1/deleteUser?id=42. - Stateless: the server keeps no context between requests. Because every request carries everything it needs (such as the auth token), you can add servers and spread the load easily.
- Uniform interface: the same conventions (methods, status codes, representations) are reused, so you can guess how to read an API you have never seen.
- Cacheable: since GET is safe, HTTP's existing caching machinery works as is.
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.
- API key: an issued string sent in a header. Simple, but the key is the permission, so keeping it secret is everything.
- Bearer token: the
Authorization: Bearer <token>form (RFC 6750). It means "admit whoever bears this ticket," and the token itself is often a JWT. A key benefit is that it can expire. - OAuth 2.0: an authorization framework (RFC 6749) for delegating limited permissions to a third-party app without handing over the user's password. It is what runs behind "Sign in with Google."
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.
| Style | Characteristics | Where it fits |
|---|---|---|
| REST | URL = resource, HTTP method = action; JSON is the norm | General-purpose Web APIs; when caching matters |
| GraphQL | The client specifies exactly which fields it wants | When each screen needs very different data |
| gRPC | Generated from a schema; fast binary transport | Internal communication between microservices |
| WebSocket | Keeps a connection open for two-way messaging | Chat, 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.