What Is an API in Plain Terms?
API stands for Application Programming Interface. That sounds intimidating, but the idea is simple: an API is a set of rules that lets two pieces of software talk to each other. It defines what you can ask for and what you'll get back — without you needing to know how the other side works internally.
The restaurant analogy
Imagine you're at a restaurant. You (the customer) want food, but you don't walk into the kitchen and cook it yourself. Instead, you talk to a waiter. You give the waiter your order from a menu, the waiter takes it to the kitchen, and later brings back your dish.
- You are the client (a website, a mobile app, or another program).
- The kitchen is the server, where the real work and data live.
- The waiter is the API — the messenger that takes your request and brings back a response.
- The menu is the API's documentation — the list of what you're allowed to ask for.
You don't need to know how the kitchen prepares the meal. You just need to know how to order. That's exactly what an API gives you: a predictable way to ask for something and receive a result.
Key idea: An API hides complexity. The weather app on your phone doesn't store global weather data — it asks a weather API for it. The API handles the hard part and hands back a clean answer.
Why Do APIs Exist?
APIs exist so that software can reuse functionality and data without rebuilding everything from scratch. They power almost everything online:
- Logging in with Google uses Google's authentication API.
- A maps widget embedded in a site pulls from a maps API.
- Online payments talk to Stripe's or PayPal's API.
- Your weather app requests live data from a weather API.
Without APIs, every developer would have to build payment processing, maps, and authentication themselves. APIs let teams focus on their own product and borrow proven services for the rest. They also create a clean boundary: the provider can change their internal code freely, as long as the API stays the same.
Client, Server & HTTP Methods
Most APIs you'll meet as a frontend developer are web APIs that communicate over HTTP — the same protocol your browser uses to load pages. Two roles are involved:
- Client — the one making the request (your browser, app, or code).
- Server — the one receiving the request and sending back a response.
When the client wants something, it sends an HTTP request to a specific URL (called an endpoint) using an HTTP method that describes the intent:
| Method | Purpose | Example |
|---|---|---|
GET | Read / retrieve data | Get a list of users |
POST | Create new data | Add a new blog post |
PUT | Replace existing data | Update a whole user profile |
PATCH | Update part of existing data | Change just an email field |
DELETE | Remove data | Delete a comment |
Tip: A handy way to remember this is CRUD — Create, Read, Update, Delete — which maps neatly onto POST, GET, PUT/PATCH, and DELETE.
REST Basics
REST (Representational State Transfer) is the most common style for building web APIs. It isn't a strict standard — it's a set of conventions that make APIs predictable. An API that follows these conventions is called RESTful.
The core ideas of REST:
- Everything is a resource identified by a URL — for example,
/usersor/users/42. - You act on resources using HTTP methods (GET to read, POST to create, and so on).
- It's stateless — each request carries everything the server needs; the server doesn't remember previous requests.
- Responses are usually JSON, making them easy to read and parse.
So GET /users/42 reads user 42, while DELETE /users/42 removes them. Same resource, different method, different meaning. That consistency is what makes REST APIs easy to learn.
Anatomy of a Request & Response
Every HTTP exchange has two halves: the request you send and the response you get back. Here's what a request looks like under the hood:
GET /users/42 HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer YOUR_TOKENA request is made of:
- Method + endpoint — what you want to do and where (
GET /users/42). - Headers — extra info like the format you accept or your credentials.
- Body (for POST/PUT/PATCH) — the data you're sending, usually as JSON.
The server replies with a response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"id": 42,
"name": "Ada Lovelace",
"email": "ada@example.com"
}A response is made of:
- Status code — a number telling you what happened (
200 OK). - Headers — metadata like the content type.
- Body — the actual data, almost always JSON.
JSON — The Language of APIs
JSON (JavaScript Object Notation) is the text format almost all modern APIs use to send data. It's lightweight, human-readable, and maps directly onto JavaScript objects and arrays.
{
"id": 42,
"name": "Ada Lovelace",
"isActive": true,
"languages": ["JavaScript", "Python"],
"profile": {
"city": "London",
"joined": 2024
}
}JSON supports a small set of types: strings, numbers, booleans (true/false), null, arrays ([ ]), and objects ({ }). In JavaScript you convert between JSON text and real objects using JSON.parse() and JSON.stringify() — though when you use fetch(), the .json() method does the parsing for you.
Watch out: JSON keys and string values must use double quotes ("name"), not single quotes. Trailing commas are not allowed. A single typo will cause a parse error.
HTTP Status Codes
Every response carries a status code that tells you, at a glance, what happened. They're grouped by the first digit:
| Range | Meaning | Common Examples |
|---|---|---|
2xx | Success | 200 OK, 201 Created |
3xx | Redirection | 301 Moved Permanently, 304 Not Modified |
4xx | Client error (your request) | 400 Bad Request, 401 Unauthorized, 404 Not Found |
5xx | Server error (their side) | 500 Internal Server Error, 503 Service Unavailable |
Quick rule: 4xx means you did something wrong (bad URL, missing token, invalid data). 5xx means the server failed and it's not your fault.
A Real fetch() Example
Let's put it all together. The browser's built-in fetch() function lets you call an API from JavaScript. Here we use JSONPlaceholder, a free public test API, to fetch a single post:
async function getPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
// Check the status code before trusting the data
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
// Parse the JSON body into a JavaScript object
const post = await response.json();
console.log(post.title);
return post;
} catch (error) {
console.error('Something went wrong:', error);
}
}
getPost();Step by step:
fetch()sends aGETrequest to the endpoint and returns a Promise.awaitpauses until the response arrives.response.okistruefor any2xxstatus — we check it before continuing.response.json()reads the body and parses the JSON into a usable object.
To send data instead, you pass a second options argument:
await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Hello', body: 'My first post', userId: 1 })
});Common mistake: fetch() only rejects on network failures, not on HTTP errors. A 404 or 500 still resolves successfully — that's why you must check response.ok yourself.
API Keys & Authentication Basics
Many APIs are free and open, but most real-world ones need to know who is calling so they can control access and limit usage. The two most common approaches you'll see:
API keys
An API key is a unique string the provider gives you. You include it with each request — often in a header or as a query parameter — to identify your app:
fetch('https://api.example.com/data', {
headers: { 'X-API-Key': 'your_api_key_here' }
});Tokens (Bearer auth)
More secure APIs issue a temporary token after you log in, which you send in the Authorization header:
fetch('https://api.example.com/profile', {
headers: { 'Authorization': 'Bearer eyJhbGciOi...' }
});Security: Never hard-code secret API keys in frontend JavaScript or commit them to a public repo — anyone can read them. Secret keys belong on a backend server or in environment variables. Public, rate-limited keys for client-side widgets are the only safe exception.
That's the whole picture: a client sends an HTTP request to an endpoint, optionally authenticated, the server responds with a status code and a JSON body, and your code reads it. Once this clicks, every API you ever touch will feel familiar — only the menu changes.