What Is an API? Here's What Happens When You Hit Send
Photo by NASA on Unsplash
Table of Contents
The Restaurant Analogy (and Why It Actually Works)
You're at a restaurant. You don't walk into the kitchen and cook your own food. You talk to a waiter, tell them what you want, and they bring it back. The kitchen has rules about what's on the menu, how to order, and what format your request needs to be in ("medium rare, no onions"). You don't need to know how the kitchen works internally. You just need to know the menu and how to talk to the waiter.
An API (Application Programming Interface) is the waiter. It's the layer between your code and someone else's system. Your code sends a request in a specific format, the API routes it to the right place, and you get back a response.
The reason this analogy holds up better than most: it captures the key insight about APIs that I missed for way too long. The kitchen doesn't care who you are or what language you speak, as long as your order follows the format. A React frontend, a Python script, a mobile app, and a curl command from a terminal can all talk to the same API. The interface is the contract — as long as you follow it, you get your data.
I didn't really understand APIs until I built one myself in my second year of coding. Reading about them felt abstract. Actually sending requests and seeing JSON come back made it click.
What Actually Happens During an API Call
Photo by Florian Olivo on Unsplash
**Step 1 — Your code builds a request.** It constructs an HTTP request with: - A **method** (GET, POST, PUT, DELETE) — GET because you're retrieving data - A **URL** (the endpoint) — `https://api.openweathermap.org/data/2.5/weather?q=London&appid=YOUR_KEY` - **Headers** — metadata like Content-Type, Authorization, Accept - Optionally, a **body** — not needed for GET, but POST/PUT requests include data here
**Step 2 — The request travels over HTTP.** Your code sends this request across the internet to the API server. The URL tells the network where to route it. The URL encoding matters here — special characters in query parameters need to be percent-encoded or the request will break.
**Step 3 — The server processes the request.** The API server receives the request, validates your API key, checks the parameters, queries its database for London's weather, and builds a response.
**Step 4 — The server sends back a response.** The response includes: - An **HTTP status code** (200 for success, 401 if your API key is wrong, 404 if the city doesn't exist) - **Response headers** (Content-Type, rate limit info, caching directives) - A **response body** — usually JSON containing the data you asked for
**Step 5 — Your code handles the response.** You parse the JSON, extract the temperature, and display it in the UI. If the status code isn't 200, you handle the error.
That's it. Every API call follows this pattern. The specifics change (different URLs, different auth methods, different data shapes), but the request-response flow is always the same.
REST APIs — The Style That Runs Most of the Web
The core ideas:
**Resources have URLs.** Everything your API exposes is a "resource" with its own URL. Users live at `/users`. A specific user lives at `/users/123`. That user's orders live at `/users/123/orders`. The URL structure tells you what you're working with.
**HTTP methods map to actions.** This is the pattern that makes REST intuitive: - `GET /users` — list all users - `GET /users/123` — get one specific user - `POST /users` — create a new user - `PUT /users/123` — replace user 123 entirely - `PATCH /users/123` — update some fields on user 123 - `DELETE /users/123` — delete user 123
Once you know this pattern, you can guess the endpoints of almost any REST API without reading the docs. Need to get all products? Probably `GET /products`. Need to create an order? Probably `POST /orders`.
**Responses are usually JSON.** The standard response format for REST APIs is JSON — a structured text format that every programming language can parse. When your API returns `{"name": "Alice", "email": "alice@example.com"}`, any language on any platform can read that. If you're not familiar with JSON syntax, the JSON formatter at ToolsFuel is handy for making raw API responses readable.
**Each request is stateless.** The server doesn't remember your previous request. Every request must include everything the server needs to process it — your authentication token, any filters or pagination parameters, everything. This simplifies server design but means you need to send your auth credentials with every request, usually as a header like `Authorization: Bearer <your-jwt-token>`. If you've worked with JWT tokens, this is where they show up in practice.
Authentication — How APIs Know Who You're
**API Keys** — The simplest method. The API gives you a unique string (your key), and you include it in every request, either as a query parameter (`?api_key=abc123`) or as a header (`X-API-Key: abc123`). The OpenWeather API, Google Maps API, and most free-tier APIs use this approach. It's easy to implement but offers minimal security — if someone gets your key, they can impersonate you.
**OAuth 2.0** — Used when your app needs to access a user's data on another service. "Sign in with Google" or "Connect your GitHub account" — that's OAuth. The flow involves redirecting the user to the provider (Google, GitHub), them granting permission, and your app receiving a temporary access token. OAuth is more complex but more secure — the user's password never touches your application.
**JWT Bearer Tokens** — After a user logs in to your own API (with username and password), the server generates a JWT containing their identity and permissions. Your frontend stores this token and includes it in the `Authorization: Bearer <token>` header with every subsequent request. The server validates the token without needing a database lookup (the token itself contains the claims), which makes this fast for APIs with many concurrent users.
My recommendation for new developers: start with API keys. They're the easiest to understand, and most public APIs you'll practice with use them. You can sign up for a free API key from services like OpenWeather, NASA, or the GitHub API in a few minutes.
One mistake I see frequently: hardcoding API keys in frontend JavaScript. Never do this. Keys in client-side code are visible to anyone who opens browser DevTools. Use environment variables on the server side, or proxy the API call through your own backend.
Making Your First API Call (It's Three Lines of Code)
Photo by Thomas Jensen on Unsplash
```javascript const response = await fetch('https://catfact.ninja/fact'); const data = await response.json(); console.log(data.fact); ```
That's it. Three lines. `fetch()` sends a GET request to the URL, `.json()` parses the response body as JSON, and you've got your data.
Let's try one with parameters — getting weather for a city:
```javascript const city = 'London'; const key = 'your_api_key_here'; const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}&units=metric`;
const response = await fetch(url); if (!response.ok) { console.error(`Error: ${response.status}`); } else { const weather = await response.json(); console.log(`${weather.name}: ${weather.main.temp}°C`); } ```
Notice the `response.ok` check — that's how you handle errors. `response.ok` is true for any 2xx status code. If the API returns 401 (bad key), 404 (city not found), or 500 (server error), you catch it here instead of trying to parse an error message as weather data.
For POST requests (sending data to the API), you add a body and headers:
```javascript const response = await fetch('https://api.example.com/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Alice', email: 'alice@example.com' }) }); const newUser = await response.json(); ```
The `Content-Type: application/json` header tells the server you're sending JSON. `JSON.stringify()` converts your JavaScript object to a JSON string. The server processes it and returns the created user (typically with an `id` field added).
I'd suggest trying these in your browser's DevTools console right now — the cat fact API doesn't need an API key, so you can test it immediately.
REST vs GraphQL vs WebSockets
**GraphQL** lets the client specify exactly what data it wants in a single request. Instead of hitting `/users/123` and getting back every field (name, email, avatar, address, preferences...), you send a query saying "give me just the name and email for user 123." The server returns only those fields. This reduces data transfer, especially for mobile apps on slow connections. The trade-off: more complexity on the server and client, and caching is harder.
**WebSockets** are for real-time bidirectional communication. REST is request-response — you ask, the server answers. WebSockets keep a connection open so the server can push data to you without being asked. Chat apps, live sports scores, multiplayer games, stock tickers — anything where data changes constantly and you need instant updates. The trade-off: persistent connections use more server resources.
Here's my rule of thumb: start with REST. It covers 90% of use cases, every developer understands it, and the tooling is mature. Switch to GraphQL when you're building a client that needs flexible data fetching from a complex backend. Use WebSockets only when you genuinely need real-time push from the server.
I spent a weekend once converting a perfectly good REST endpoint to GraphQL because it seemed cooler. It wasn't. The REST version was simpler, easier to cache, and the frontend only needed three fields anyway. Don't add complexity because a technology is trendy.
Free APIs to Practice With
- **catfact.ninja** — random cat facts, no auth needed - **jsonplaceholder.typicode.com** — fake REST API for testing (users, posts, comments), no auth - **pokeapi.co** — Pokemon data API, no auth, great for practice - **openweathermap.org** — weather data, free tier with API key - **api.github.com** — GitHub's public API, no auth for public repos (rate limited) - **restcountries.com** — country data, no auth
My advice: pick one, build something small. Don't just read the docs — actually write the fetch call, parse the response, and display the data. I learned more about APIs in one afternoon of building a Pokemon search than in a week of reading tutorials.
When you're debugging API responses, ToolsFuel's JSON formatter is useful for prettifying raw JSON output, and the JWT decoder helps when you're working with authentication tokens. Having those bookmarked saves time when you're in the middle of a debugging session and need to quickly inspect what came back from a request.
Frequently Asked Questions
What does API stand for and what is it in simple terms?
API stands for Application Programming Interface. In simple terms, it's a way for two pieces of software to talk to each other. When your weather app shows today's forecast, it's using an API to ask a weather service for the data. When you log in with Google on a website, that site is using Google's API to verify your identity. The API defines what questions you can ask, how to ask them, and what the answers look like. You don't need to know how the other system works internally — you just need to follow the interface.
What is the difference between REST and GraphQL APIs?
REST APIs use fixed endpoints — each URL returns a predefined set of data. GET /users/123 returns all of user 123's information. GraphQL uses a single endpoint where the client specifies exactly what fields it wants in a query. So instead of getting 20 fields when you only need 3, you request just those 3. REST is simpler to build and cache. GraphQL is more efficient for complex apps with varying data needs. Most APIs you'll encounter are REST because it's been the standard for twenty years. GraphQL is growing but it adds complexity that isn't always justified.
How do I get an API key?
Most APIs that require keys offer a free signup on their website. Go to the API provider's developer portal, create an account, and they'll generate a key for you. It usually takes a few minutes. The key is just a long string of characters that identifies your application. Include it in your requests as a header or query parameter. Keep it private — don't commit API keys to public GitHub repos or include them in client-side JavaScript. Use environment variables to store keys on the server side.
Why do APIs return JSON instead of something else?
JSON (JavaScript Object Notation) became the standard because it's human-readable, lightweight, and natively supported in JavaScript — the language that runs in every web browser. Before JSON, APIs commonly used XML, which is more verbose and harder to parse. JSON looks like this: {"name": "Alice", "age": 30}. Every programming language has a built-in JSON parser, which means the same API response can be consumed by Python, JavaScript, Java, Go, Ruby, or any other language without special libraries. It's the closest thing to a universal data format.
What is a webhook and how is it different from an API?
A regular API call is like checking your mailbox — you go to the server and ask for data. A webhook is like having mail delivered to your door — the server sends data to you when something happens. With a normal API, your code polls the server repeatedly asking 'did anything change?' With a webhook, you give the server a URL and it calls that URL automatically when an event occurs (like a payment completing or a form being submitted). Webhooks are more efficient for event-driven workflows because they eliminate constant polling.
Can I build my own API?
Yes, and it's one of the best ways to learn how APIs work. If you know JavaScript, you can build a simple REST API with Express.js in about 20 lines of code. Python developers can use Flask or FastAPI. The basic pattern is: define routes (URLs), write handler functions that process requests, and send back JSON responses. Start with a simple CRUD API — create, read, update, delete operations on a list of items stored in memory. Once that works, add a database. Then add authentication. Each step teaches you something concrete about how production APIs work.
Try ToolsFuel
23+ free online tools for developers, designers, and everyone. No signup required.
Browse All Tools