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

Why the front end should not talk to the database directly

  1. 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.
  2. Rules. The API checks that a request makes sense: is this user allowed to see that order? Is the email valid?
  3. 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 requestTypical SQL
GET /api/notesSELECT
POST /api/notesINSERT
PUT or PATCH /api/notes/7UPDATE ... WHERE id = 7
DELETE /api/notes/7DELETE ... WHERE id = 7

This pairing is why CRUD and web APIs are often taught together.

Common beginner mistakes

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.

Related pages on this site