Second project: a blog API

We will build an API for a blog with Flask and SQLite, with data validation, tests and a simple JavaScript page. You will need what you learned in the databases and REST API sections. It takes about an hour.

Boys selling newspapers on the Brooklyn Bridge, 1908

What you will get

All the code fits into a single app.py file. You can run the last example right on this page.

0 of 7 steps done

Project steps

Tick off what you have done: your progress is saved in the browser.

  1. Step 1. Create the project

    A new folder with its own environment, as in the first project.

    Terminal
    mkdir blog-api
    cd blog-api
    python -m venv .venv
    .venv\Scripts\activate
    pip install flask pytest

    On macOS and Linux the environment is activated with source .venv/bin/activate.

  2. Step 2. Connect the database

    The connection opens for the duration of a request and closes at the end. The table is created on the first run if it does not exist yet. The create_app function lets tests use a separate database.

    app.py
    import sqlite3
    
    from flask import Flask, g, jsonify, request
    
    SCHEMA = """
    CREATE TABLE IF NOT EXISTS posts (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        body TEXT NOT NULL,
        created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
    )
    """
    
    def create_app(database="blog.db"):
        app = Flask(__name__)
    
        def db():
            if "db" not in g:
                g.db = sqlite3.connect(database)
                g.db.row_factory = sqlite3.Row
                g.db.execute(SCHEMA)
            return g.db
    
        @app.teardown_appcontext
        def close_db(error):
            connection = g.pop("db", None)
            if connection is not None:
                connection.close()
    
        # routes from the next steps go here
    
        return app
  3. Step 3. Add data validation

    The function returns either clean data or an error text. Put it above create_app so that it is easy to test on its own.

    app.py
    def validate_post(data):
        if not isinstance(data, dict):
            return None, "A JSON object is required"
        title = str(data.get("title", "")).strip()
        body = str(data.get("body", "")).strip()
        if not title or len(title) > 120:
            return None, "Title is required, at most 120 characters"
        if not body:
            return None, "Body is required"
        return {"title": title, "body": body}, None
  4. Step 4. Make the list and creating a record

    Values are passed through ? marks, so the database protects the query from SQL injection itself. Never put user data into SQL with an f-string.

    app.py
        @app.get("/posts")
        def list_posts():
            rows = db().execute("SELECT * FROM posts ORDER BY id DESC").fetchall()
            return jsonify([dict(row) for row in rows])
    
        @app.post("/posts")
        def create_post():
            post, error = validate_post(request.get_json(silent=True))
            if error:
                return {"error": error}, 400
            cursor = db().execute(
                "INSERT INTO posts (title, body) VALUES (?, ?)",
                (post["title"], post["body"]),
            )
            db().commit()
            row = db().execute("SELECT * FROM posts WHERE id = ?", (cursor.lastrowid,)).fetchone()
            return dict(row), 201
  5. Step 5. Make reading, changing and deleting

    If there is no such record, we return a 404 error instead of crashing.

    app.py
        @app.get("/posts/<int:post_id>")
        def get_post(post_id):
            row = db().execute("SELECT * FROM posts WHERE id = ?", (post_id,)).fetchone()
            if row is None:
                return {"error": "Post not found"}, 404
            return dict(row)
    
        @app.put("/posts/<int:post_id>")
        def update_post(post_id):
            post, error = validate_post(request.get_json(silent=True))
            if error:
                return {"error": error}, 400
            cursor = db().execute(
                "UPDATE posts SET title = ?, body = ? WHERE id = ?",
                (post["title"], post["body"], post_id),
            )
            db().commit()
            if cursor.rowcount == 0:
                return {"error": "Post not found"}, 404
            return get_post(post_id)
    
        @app.delete("/posts/<int:post_id>")
        def delete_post(post_id):
            cursor = db().execute("DELETE FROM posts WHERE id = ?", (post_id,))
            db().commit()
            if cursor.rowcount == 0:
                return {"error": "Post not found"}, 404
            return "", 204

    Running on your computer: flask --app "app:create_app()" run --debug.

  6. Step 6. Write tests

    Run them with the pytest command. The tmp_path fixture gives a temporary folder, so the tests do not touch the real database.

    test_app.py
    import pytest
    
    from app import create_app
    
    @pytest.fixture
    def client(tmp_path):
        return create_app(tmp_path / "test.db").test_client()
    
    def test_create_and_read(client):
        created = client.post("/posts", json={"title": "Hello", "body": "Text"})
        assert created.status_code == 201
        post_id = created.json["id"]
        assert client.get(f"/posts/{post_id}").json["title"] == "Hello"
    
    def test_empty_title_rejected(client):
        assert client.post("/posts", json={"title": " ", "body": "Text"}).status_code == 400
    
    def test_delete(client):
        post_id = client.post("/posts", json={"title": "A", "body": "B"}).json["id"]
        assert client.delete(f"/posts/{post_id}").status_code == 204
        assert client.get(f"/posts/{post_id}").status_code == 404
  7. Step 7. Add a page

    Put the file in the static folder, and it opens at /static/index.html. The post text is output through textContent, so nobody can inject a script through it.

    static/index.html
    <!doctype html>
    <html lang="en">
    <meta charset="utf-8">
    <title>Blog</title>
    <h1>Blog</h1>
    <form id="form">
      <input name="title" placeholder="Title" required>
      <textarea name="body" placeholder="Text" required></textarea>
      <button>Publish</button>
    </form>
    <div id="posts"></div>
    <script>
      const posts = document.getElementById("posts");
      const form = document.getElementById("form");
    
      async function load() {
        const items = await (await fetch("/posts")).json();
        posts.replaceChildren(...items.map((post) => {
          const article = document.createElement("article");
          const title = document.createElement("h2");
          const body = document.createElement("p");
          title.textContent = post.title;
          body.textContent = post.body;
          article.append(title, body);
          return article;
        }));
      }
    
      form.addEventListener("submit", async (event) => {
        event.preventDefault();
        const response = await fetch("/posts", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(Object.fromEntries(new FormData(form))),
        });
        if (response.ok) {
          form.reset();
          load();
        }
      });
    
      load();
    </script>
    </html>

All the code and running it

Here is the whole app.py file and a short check at the end. The database is created in a temporary file.

app.py in full
import sqlite3
import tempfile
from pathlib import Path

from flask import Flask, g, jsonify, request

SCHEMA = """
CREATE TABLE IF NOT EXISTS posts (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    title TEXT NOT NULL,
    body TEXT NOT NULL,
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
)
"""

def validate_post(data):
    if not isinstance(data, dict):
        return None, "A JSON object is required"
    title = str(data.get("title", "")).strip()
    body = str(data.get("body", "")).strip()
    if not title or len(title) > 120:
        return None, "Title is required, at most 120 characters"
    if not body:
        return None, "Body is required"
    return {"title": title, "body": body}, None

def create_app(database="blog.db"):
    app = Flask(__name__)

    def db():
        if "db" not in g:
            g.db = sqlite3.connect(database)
            g.db.row_factory = sqlite3.Row
            g.db.execute(SCHEMA)
        return g.db

    @app.teardown_appcontext
    def close_db(error):
        connection = g.pop("db", None)
        if connection is not None:
            connection.close()

    @app.get("/posts")
    def list_posts():
        rows = db().execute("SELECT * FROM posts ORDER BY id DESC").fetchall()
        return jsonify([dict(row) for row in rows])

    @app.post("/posts")
    def create_post():
        post, error = validate_post(request.get_json(silent=True))
        if error:
            return {"error": error}, 400
        cursor = db().execute(
            "INSERT INTO posts (title, body) VALUES (?, ?)",
            (post["title"], post["body"]),
        )
        db().commit()
        row = db().execute("SELECT * FROM posts WHERE id = ?", (cursor.lastrowid,)).fetchone()
        return dict(row), 201

    @app.get("/posts/<int:post_id>")
    def get_post(post_id):
        row = db().execute("SELECT * FROM posts WHERE id = ?", (post_id,)).fetchone()
        if row is None:
            return {"error": "Post not found"}, 404
        return dict(row)

    @app.put("/posts/<int:post_id>")
    def update_post(post_id):
        post, error = validate_post(request.get_json(silent=True))
        if error:
            return {"error": error}, 400
        cursor = db().execute(
            "UPDATE posts SET title = ?, body = ? WHERE id = ?",
            (post["title"], post["body"], post_id),
        )
        db().commit()
        if cursor.rowcount == 0:
            return {"error": "Post not found"}, 404
        return get_post(post_id)

    @app.delete("/posts/<int:post_id>")
    def delete_post(post_id):
        cursor = db().execute("DELETE FROM posts WHERE id = ?", (post_id,))
        db().commit()
        if cursor.rowcount == 0:
            return {"error": "Post not found"}, 404
        return "", 204

    return app

# Check without a real server
with tempfile.TemporaryDirectory() as folder:
    client = create_app(Path(folder) / "blog.db").test_client()
    print("Empty title:", client.post("/posts", json={"title": "", "body": "x"}).status_code)
    created = client.post("/posts", json={"title": "First post", "body": "Hello!"})
    print("Created:", created.status_code, created.json["title"])
    post_id = created.json["id"]
    print("Updated:", client.put(f"/posts/{post_id}", json={"title": "New", "body": "Text"}).json["title"])
    print("List:", [post["title"] for post in client.get("/posts").json])
    print("Deleted:", client.delete(f"/posts/{post_id}").status_code)
    print("Read again:", client.get(f"/posts/{post_id}").status_code)

What to add on your own

These ideas reinforce what you learned in other sections.

  • Pagination: the ?limit=10&offset=20 parameters and the SQL LIMIT ? OFFSET ?.
  • Author login: posts can be created and deleted only after authentication.
  • Search by title with LIKE ?.
  • Deployment to PythonAnywhere: put application = create_app("/home/username/blog-api/blog.db") in the WSGI file.

Test yourself

Take the final test and get a learning certificate.