Create a REST API using Python which stores data in a database and retrieves the data upon a GET request.
Not applicable
Assistant
Problem: Create a REST API using Python which stores data in a database and retrieves the data upon a GET request.
Not applicable
Approach: Python
Let me implement this solution.
Here is a complete, step-by-step solution to create a REST API using Python, Flask (a micro web framework), and SQLite (a built-in database).
Prerequisites
You will need to install Flask. Open your terminal or command prompt and run:
bash
pip install flask
The Solution
Create a file named app.py and paste the following code. This code sets up the application, defines the database structure, and creates the endpoints to store and retrieve data.
python
import sqlite3
from flask import Flask, request, jsonify
app = Flask(__name__)
DB_NAME = "data.db"
# --- Database Helper Functions ---
def init_db():
"""Initializes the database and creates the table if it doesn't exist."""
with sqlite3.connect(DB_NAME) as conn:
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL
)
""")
conn.commit()
def get_db_connection():
"""Creates a database connection."""
conn = sqlite3.connect(DB_NAME)
# This allows us to access columns by name (row['name'])
conn.row_factory = sqlite3.Row
return conn
# --- API Routes ---
@app.route('/users', methods=['POST'])
def add_user():
"""Stores data in the database."""
data = request.get_json()
if not data or 'name' not in data or 'email' not in data:
return jsonify({'error': 'Invalid data. Name and Email required.'}), 400
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)",
(data['name'], data['email']))
conn.commit()
new_id = cursor.lastrowid
conn.close()
return jsonify({'message': 'User created', 'id': new_id}), 201
@app.route('/users', methods=['GET'])
def get_users():
"""Retrieves all data from the database."""
conn = ge