How an API Sits Between Your App and Its Database
Many beginner projects have a front end, such as a web page or a phone app, and a database. They almost never talk to each other directly. In between sits an API. This page explains what that middle layer does, with a tiny example.
The three layers
Front end (browser or app) -> API (server code) -> Database
shows data checks and decides stores data
- The front end is what users see and tap.
- The API (application programming interface) is server code that receives requests, applies rules and talks to the database.
- The database stores the data and answers queries.
Why the front end should not talk to the database directly
- Security. To connect directly, the front end would need database credentials. Anything shipped to a browser or phone can be read by users, so those credentials would leak.
- Rules. The API checks that a request makes sense: is this user allowed to see that order? Is the email valid?
- Flexibility. You can change the database structure without changing every app, as long as the API's answers stay the same.
A tiny example
The front end asks for a list of notes:
GET /api/notes
The API runs a query and returns JSON:
@app.get("/api/notes")
def list_notes():
rows = conn.execute("SELECT id, body FROM notes ORDER BY id DESC LIMIT 20").fetchall()
return [{"id": r[0], "body": r[1]} for r in rows]
The front end receives:
[{"id": 7, "body": "Buy milk"}, {"id": 6, "body": "Call Ana"}]
Adding data through the API
@app.post("/api/notes")
def add_note(body: str):
with conn:
conn.execute("INSERT INTO notes (body) VALUES (?)", (body,))
return {"ok": True}
The placeholder ? keeps whatever the user typed from changing the SQL command.
How requests map to SQL
| HTTP request | Typical SQL |
|---|---|
| GET /api/notes | SELECT |
| POST /api/notes | INSERT |
| PUT or PATCH /api/notes/7 | UPDATE ... WHERE id = 7 |
| DELETE /api/notes/7 | DELETE ... WHERE id = 7 |
This pairing is why CRUD and web APIs are often taught together.
Common beginner mistakes
- returning every column, including private ones such as password hashes
- trusting ids sent by the front end without checking the user may access them
- building SQL from request values with string gluing
- opening a new database connection for every request without closing it
Where next
Our in-depth guide that follows one web form to the database shows the same journey for a sign-up form, and users and permissions explains why the API's database account should have limited rights.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.