Technology

What Is an API?

An API is a defined way for one program to ask another program for something. You send a request in an agreed format, the other side sends back a structured answer — usually JSON — and neither side needs to know how the other works internally.

The everyday example: when a weather app shows a forecast, it did not calculate it. It asked a weather service's API for the forecast for your location, and the service replied with data the app then displayed.

"API" gets explained with restaurant-waiter metaphors that leave you no better able to use one. This guide explains what is actually going over the wire, what the words in the documentation mean, and how to read an API response — with a real request you can run yourself.

The contract, not the code

The important word in "application programming interface" is interface. An API is a promise about what you can ask for and what you will get back. It deliberately hides how the answer is produced.

That hiding is the point. A weather service can rewrite its entire forecasting system, and as long as the API still accepts the same requests and returns the same shape of data, every app using it keeps working. The interface is a stable surface over changing machinery.

This is why APIs are described as contracts. Break the contract — rename a field, change a data type — and you break every program that relied on it, which is why well-run APIs version their changes rather than altering existing behaviour.

What a request actually looks like

Most APIs you will meet are REST APIs over HTTP, which means a request is the same kind of thing your browser sends when it loads a page. It has four parts:

PartWhat it doesExample
MethodThe kind of operationGET
URLWhich resourcehttps://api.example.com/v1/users/42
HeadersMetadata: auth, formatAuthorization: Bearer abc123
BodyData you are sending (not used by GET){"name": "Ada"}

The methods

Four cover almost everything:

  • GET — read something. Should never change anything on the server.
  • POST — create something new.
  • PUT / PATCH — update something. PUT replaces the whole thing, PATCH changes part of it.
  • DELETE — remove something.

The rule that matters: GET must be safe to repeat. Browsers, caches and crawlers assume a GET has no side effects, so an API that deletes a record on GET /delete?id=5 will eventually have records deleted by a crawler following links. This is a real failure mode, not a theoretical one. The MDN reference on HTTP methods is the place to check the exact semantics.

Status codes: what the answer means before you read it

Every response carries a three-digit code. The first digit tells you the category:

RangeMeaningCommon ones
2xxIt worked200 OK · 201 Created · 204 No Content
3xxLook elsewhere301 Moved Permanently · 304 Not Modified
4xxYour request was wrong400 Bad Request · 401 Unauthorized · 403 Forbidden · 404 Not Found · 429 Too Many Requests
5xxTheir server failed500 Internal Server Error · 503 Service Unavailable

The 4xx/5xx split is the most useful distinction when something breaks: 4xx means fix your request, 5xx means the problem is at their end. Retrying a 400 will fail identically forever; retrying a 503 after a pause often succeeds.

Two that confuse people. 401 versus 403: 401 means "I do not know who you are" (missing or bad credentials), 403 means "I know who you are and you are not allowed" (valid credentials, insufficient permission). And 429 means you are being rate limited — you are sending too many requests, and the response usually includes a header telling you how long to wait. See MDN's HTTP status code reference for the full list.

Try one right now

Open a terminal and run this. It hits a free public API that needs no key:

curl https://api.github.com/repos/python/cpython

You get back a large JSON object. Ask for one field with a bit of JavaScript instead:

fetch('https://api.github.com/repos/python/cpython')
  .then(r => r.json())
  .then(d => console.log(d.stargazers_count, d.language));

That is the whole loop: a URL, a response, a field you care about. Everything else — authentication, pagination, rate limits — is detail layered on top of those three things.

If the JSON is hard to read, paste it into our JSON formatter, which indents it and points at the exact position of any syntax error.

Authentication

Most useful APIs need to know who you are. Three common schemes:

  • API key — a long string you send with each request, usually in a header. Simple, and identifies the application rather than a person.
  • Bearer tokenAuthorization: Bearer <token>. Often short-lived and refreshed.
  • OAuth — the flow behind "Sign in with Google". The user grants your app limited access without ever giving it their password.

The rule that matters more than any of the detail: never put an API key in front-end JavaScript. Anything the browser can read, a user can read — "view source" is enough. Keys belong on a server you control, which then makes the call on the user's behalf. Keys leaked in client-side code and public repositories are one of the most common ways services get abused and bills get run up.

Reading API documentation

Good documentation has a predictable shape, and knowing it makes unfamiliar APIs fast to pick up:

  1. Base URL — what every endpoint is appended to, often with a version: https://api.example.com/v1.
  2. Authentication — what to send and where. Do this before trying anything else.
  3. Endpoints — the list of things you can ask for, with methods and parameters.
  4. Rate limits — how many requests per minute or hour. Ignore this and you will get 429s in production.
  5. Response examples — the exact shape of what comes back. The most useful section, and often the one people skip.

Start with the smallest possible request that returns anything at all. Getting one successful 200 proves your base URL, authentication and network path all work; after that you are only changing parameters.

Common mistakes

  • Not checking the status code. Parsing the body without checking whether the request succeeded gives confusing errors, because an error body has a different shape from a success body.
  • Ignoring pagination. Most list endpoints return the first 20–100 items, not everything. If a count looks suspiciously round, you are seeing page one.
  • Assuming fields exist. Optional fields may be absent or null. Reading data.user.address.city crashes when address is missing.
  • Hammering the API in a loop. Respect rate limits, and back off when you get a 429 rather than retrying immediately.
  • Hard-coding the key. Use an environment variable, and never commit it — see our Git and GitHub guide on why deleting a committed secret does not remove it.

To build something that uses one, HTML for beginners covers the page itself and Git and GitHub covers keeping the code safe while you experiment.

Frequently asked questions

What is an API in simple terms?

A defined way for one program to request something from another. You send a request in an agreed format, and you get back structured data — usually JSON — without needing to know how the other program produced it.

What is the difference between an API and a website?

Both are served over HTTP, but a website returns HTML meant for a person to look at, while an API returns structured data meant for a program to process. The same server often provides both from the same underlying information.

What does REST mean?

REST is a style of API design that uses standard HTTP methods against URLs that represent resources — GET /users/42 to read user 42, DELETE /users/42 to remove them. Most public web APIs follow it loosely rather than strictly.

What is the difference between 401 and 403?

401 Unauthorized means the server does not know who you are — credentials are missing, malformed or expired. 403 Forbidden means it does know who you are and you are not permitted to do this. Sending better credentials fixes a 401; only a permission change fixes a 403.

Why am I getting a 429 error?

You have exceeded the API's rate limit. Slow down, and check the response headers, which usually indicate how long to wait before retrying. Requests in a tight loop are the usual cause.

Is it safe to put an API key in my JavaScript?

No. Anything sent to the browser is visible to anyone who opens developer tools. Keep keys on a server you control and have it make the request, returning only the result to the browser.

Conclusion

An API is a request, a response and a contract about their shape. Once you can read a status code and pick a field out of JSON, most of what remains is reading documentation carefully — particularly the response examples and the rate limits.

Run the curl command above against a real API. Fifteen minutes of poking at a live response teaches more than any metaphor about waiters.

Comments