Tuesday, March 5, 2024

Barebone Quart API from Sqlite DB

import asyncio
import sqlite3
from quart import Quart

app = Quart(__name__)

async def connect_db():
    conn = sqlite3.connect("your_database.db")
    conn.row_factory = sqlite3.Row
    return conn

async def fetch_data(column1):
    async with connect_db() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT ?, column2 FROM your_table", (column1,))
        data = cursor.fetchall()
    return [dict(row) for row in data]

@app.route("/api/data/<column_name>")
async def get_data(column_name):
    data = await fetch_data(column_name)
    return data  # Return the list of dictionaries directly

if __name__ == "__main__":
    app.run(debug=True)

Here, the get_data function directly returns the list of dictionaries obtained from the database, and Quart automatically handles the serialization to JSON format before sending the response.

However, using jsonify offers some advantages:

  • Consistency: It provides a consistent way to handle different data structures, ensuring they are all converted to JSON format correctly.
  • Customization: It allows for additional options like specifying status codes, setting custom headers, or customizing the JSON serialization if needed.

Therefore, while jsonify isn't strictly required in this case, it can improve code clarity and maintainability, especially for larger projects or when dealing with diverse data structures.

or with jsonify (not necessary)

import asyncio
import sqlite3
from quart import Quart, jsonify

app = Quart(__name__)

async def connect_db():
    conn = sqlite3.connect("your_database.db")
    conn.row_factory = sqlite3.Row
    return conn

async def fetch_data(column1):
    async with connect_db() as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT ?, column2 FROM your_table", (column1,))  # Dynamic query
        data = cursor.fetchall()
    return [dict(row) for row in data]

@app.route("/api/data/<column_name>")
async def get_data(column_name):
    data = await fetch_data(column_name)
    return jsonify(data)

if __name__ == "__main__":
    app.run(debug=True)

How to Use:

Now, you would access the API by providing the first column name as part of the URL. For example:

  • /api/data/name (assuming the first column is named "name")
  • /api/data/age (assuming the first column is named "age")