
Last updated: December 3, 2026
Every time you sign in with a Google account, pay through a checkout page or open a weather app, one program is asking another program for something. The set of rules for that conversation is an API. Most explanations either bury you in definitions or jump straight into code. This one builds the mental model first, then shows a working request and response, then compares the four styles you will meet at work.
The short answer
What an API is, with a restaurant
You do not walk into a restaurant kitchen and cook your own meal. You tell the waiter what you want, the waiter takes the order to the kitchen, and the food comes back the same way. The waiter is the API. The menu is its documentation: it lists what you can ask for and how. The kitchen can change its stove, its staff or its recipes, and as long as the menu and the plates stay the same, you never notice.
A real example: when a shop offers "pay with a card" through a payment provider, the shop does not touch your card details. It sends a request to the provider's API, the provider charges the card and replies with success or failure. The shop only ever sees the reply.
The request and response cycle
- A client, which could be an app, a browser or a script, sends a request to a specific address. The request says what it wants: read something, create something, change something, delete something.
- The API checks who is asking, if the endpoint needs that.
- The server does the work.
- The API sends back a response with a status code (success, error, not found) and usually some data.
Here is a real one. This code starts a tiny local server with one endpoint, GET /api/books/<id>, and calls it twice using only Python's standard library:
import json, threading, urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, HTTPServer
BOOKS = {7: {"id": 7, "title": "Clean Code", "author": "Robert C. Martin", "available": True}}
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
book = BOOKS.get(int(self.path.rsplit("/", 1)[1]))
self.send_response(200 if book else 404)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(json.dumps(book or {"error": "not found"}).encode())
server = HTTPServer(("127.0.0.1", 0), Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{server.server_port}"
def call(path):
try:
r = urllib.request.urlopen(base + path)
print(r.status, r.reason, r.headers["Content-Type"], r.read().decode())
except urllib.error.HTTPError as e:
print(e.code, e.reason, e.headers["Content-Type"], e.read().decode())
call("/api/books/7")
call("/api/books/99")
Running it printed:
200 OK application/json {"id": 7, "title": "Clean Code", "author": "Robert C. Martin", "available": true}
404 Not Found application/json {"error": "not found"}
Two things to notice. The status code tells the client what happened before it reads any data: 200 means it worked, 404 means that book does not exist. And the response body is JSON, a text format both sides understand regardless of the language they are written in.
Why APIs matter
- Reuse. You do not build a payments system, a map service or an SMS gateway from scratch. You call one.
- A clear boundary. An API exposes what a partner needs without handing over your database.
- Independent scaling. Modern systems are many small services that talk through APIs, so one busy service can grow without touching the others.
- One backend, many clients. An iOS app, an Android app and a web dashboard can all call the same API.
Four kinds of API by who can use them
- Public (open) APIs. Anyone can sign up, usually get an API key and start calling. Mapping, weather and payment services are typical examples.
- Partner APIs. Shared with specific business partners under an agreement, often with extra security such as OAuth tokens or IP restrictions.
- Internal (private) APIs. Used inside one organization between its own systems.
- Composite APIs. Combine several calls into one request, so a client gets what it needs in one round trip instead of four.
REST, SOAP, GraphQL and gRPC compared
| Style | Data format | Good for | Main trade-off |
|---|---|---|---|
| REST | Usually JSON | Web and mobile apps, public APIs | Can return too much or too little data per call |
| SOAP | XML | Enterprise, banking and legacy integrations | Verbose and heavier to implement |
| GraphQL | JSON | Complex data with several kinds of client | Steeper learning curve; HTTP caching is harder |
| gRPC | Protocol Buffers (binary) | Fast service-to-service calls | Not directly callable from a browser without a proxy layer |
REST
REST stands for Representational State Transfer. A REST API exposes resources at URLs such as /api/books/7 and uses standard HTTP methods on them: GET reads, POST creates, PUT replaces, PATCH changes part of a resource and DELETE removes it. A key idea is that requests are stateless: each one carries everything the server needs, so any server in a group can answer it. REST is the sensible default for most web and mobile projects, because every language and tool can speak HTTP.
The weak point is data shape. If an endpoint returns a whole user object but you only need the name, you fetched too much. If you need data from three resources, you make three calls.
SOAP
SOAP is an older, more formal protocol that defines its messages in XML. The W3C specification describes it as a framework for exchanging structured information that can run over a variety of underlying protocols. You will mostly meet it when integrating with banks, insurers, government systems and older enterprise software. If a system you must connect to speaks SOAP, you usually do not get to choose. Libraries in most languages can generate the boilerplate from its WSDL description file.
GraphQL
GraphQL lets the client describe exactly the fields it wants, and the server returns that shape. Where REST might need two calls for a book and its author, one GraphQL query can fetch both:
query {
book(id: 7) {
title
author { name }
}
}
That fits products with several kinds of client, such as a phone app and a web app, that need different slices of the same data. The costs are a schema to design and maintain and weaker out-of-the-box HTTP caching, because queries typically go to one endpoint as POST requests rather than to many cacheable URLs.
gRPC
gRPC is a remote procedure call framework. Instead of thinking in resources, you define services and methods in a .proto file, and tools generate client and server code in many languages. Messages are encoded with Protocol Buffers, a compact binary format. It supports streaming in either direction, which makes it popular for communication between internal services where speed matters.
service BookService {
rpc GetBook (BookRequest) returns (BookResponse);
rpc ListBooks (ListBooksRequest) returns (stream BookResponse);
}
How to choose
- A public or general-purpose API for web and mobile? REST.
- Several different clients that each need different fields from a connected data model? Consider GraphQL, perhaps on top of existing services.
- Many internal services where latency and payload size matter? Look at gRPC.
- Integrating with a bank, government or older enterprise system? Expect SOAP and learn enough to work with it.
Real systems often use more than one. A company might offer REST publicly, GraphQL to its own apps and gRPC between internal services. They solve different problems at different layers.
Five ideas every beginner should know
1. Authentication vs authorization
Authentication asks who you are, usually proved with an API key, a token or OAuth. Authorization asks what you are allowed to do once you are known. A key can get you through the door while your account level decides which rooms you can enter. OAuth 2.0 is the common standard for letting one app act on your behalf at another service without ever seeing your password.
2. HTTP status codes
| Code | Meaning | When you see it |
|---|---|---|
| 200 OK | Success | A read returned data |
| 201 Created | Resource created | A POST succeeded |
| 400 Bad Request | Invalid input | The request was malformed |
| 401 Unauthorized | Not authenticated | Missing or invalid credentials |
| 403 Forbidden | Not allowed | You are known, but lack permission |
| 404 Not Found | No such resource | The id or path does not exist |
| 429 Too Many Requests | Rate limit hit | You called too often |
| 500 Internal Server Error | Server fault | The provider's side broke |
3. Rate limiting
Providers cap how many calls you can make in a period, to protect the service. If you receive a 429, slow down and retry later, ideally waiting longer after each failure.
4. Versioning
APIs change. A version in the URL or a header, like /v2/books, lets existing clients keep working while new ones use the new shape.
5. Keep secrets out of your code
Never commit an API key to a public repository or put it in front-end code that any visitor can read. Keep keys in environment variables or a secrets manager, and rotate any key that leaks.
Where to go next
- Choosing a Database: Relational, Document, Key-Value, Graph and More
- SQL for Beginners: The Core Commands, With Examples You Can Run
We'd love to hear your thoughts! Leave a comment below
and share your experience or questions.