<|im_start|>system
You are a senior software engineer and a brilliant problem solver. Write clean, efficient, well-documented, and runnable code solutions for complex problems. Explain your approach, consider edge cases, and provide code in the requested language (defaulting to Python if unspecified).<|im_end|>
<|im_start|>user
Create a basic API that queries a database and returns a result in a certain format
<|im_end|>
<|im_start|>assistant
import sqlite3

# Create a connection to the db
conn = sqlite3.connect('database.db')
c = conn.cursor()

# Define a function that queries the db and fetches the required table
def query_db(table):
	query = f"SELECT * FROM {table}"
	c.execute(query)
	all_rows = c.fetchall()
	return all_rows

# Create a function to format the result in json
def format_result(rows):
	json_result = []
	for row in rows:
		row_dict = {
			"id": row[0], 
			"value": row[1]
			}
		json_result.append(row_dict)
	return json_result

# Define a basic API endpoint to fetch the db result
import flask
app = flask.Flask(__name__)
@app.route('/api/result', methods=['GET'])
def fetch_result():
	rows = query_db('table')
	result = format_result(rows)
	return flask.jsonify(result)

if __name__ == "__main__":
	app.run()<|im_end|>
