Build a REST API in Flask
Now, let's build a REST API in Flask using the SQLite database example.db
that we created earlier.
In the app.py
file, add the following code to import the required modules:
from flask import Flask, jsonify, request
import sqlite3
Add the following code to create the Flask application:
## Create the Flask application
app = Flask(__name__)
Now, let's define the endpoints for our REST API:
Endpoint to retrieve all users
## Endpoint to retrieve all users
@app.route('/users', methods=['GET'])
def get_users():
## Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
## Execute the SQL query to retrieve all users
cursor.execute('SELECT * FROM users')
users = cursor.fetchall()
## Close the cursor and the database connection
cursor.close()
conn.close()
## Return the users as JSON
return jsonify(users)
In this code, we first connect to the SQLite database using the connect()
method. Then, we create a cursor object to execute SQL statements using the cursor()
method. Next, we execute the SQL query to retrieve all users from the "users" table using the execute()
method. Finally, we close the cursor and the database connection using the close()
method and return the users as JSON using the jsonify()
method.
Endpoint to retrieve a specific user by ID
## Endpoint to retrieve a specific user by ID
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
## Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
## Execute the SQL query to retrieve the user by ID
cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
user = cursor.fetchone()
## Close the cursor and the database connection
cursor.close()
conn.close()
## Check if the user exists
if user:
return jsonify(user)
else:
return jsonify({'message': 'User not found'}), 404
This endpoint is similar to the previous one, except that it retrieves a specific user by ID instead of all users. We use the fetchone()
method to retrieve a single user from the "users" table.
Endpoint to create a new user
## Endpoint to create a new user
@app.route('/users', methods=['POST'])
def create_user():
## Get the user data from the request body
data = request.get_json()
name = data['name']
email = data['email']
## Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
## Execute the SQL query to insert a new user
cursor.execute('INSERT INTO users (name, email) VALUES (?, ?)', (name, email))
conn.commit()
## Close the cursor and the database connection
cursor.close()
conn.close()
## Return a success message
return jsonify({'message': 'User created successfully'})
This endpoint is used to create a new user in the "users" table. We use the get_json()
method to get the user data from the request body. Then, we use the execute()
method to insert the new user into the "users" table.
Endpoint to update an existing user
## Endpoint to update an existing user
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
## Get the updated user data from the request body
data = request.get_json()
name = data['name']
email = data['email']
## Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
## Execute the SQL query to update the user
cursor.execute('UPDATE users SET name = ?, email = ? WHERE id = ?', (name, email, user_id))
conn.commit()
## Close the cursor and the database connection
cursor.close()
conn.close()
## Return a success message
return jsonify({'message': 'User updated successfully'})
This endpoint is used to update an existing user in the "users" table. We use the get_json()
method to get the updated user data from the request body. Then, we use the execute()
method to update the user in the "users" table.
Endpoint to delete a user
## Endpoint to delete a user
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
## Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
## Execute the SQL query to delete the user
cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
conn.commit()
## Close the cursor and the database connection
cursor.close()
conn.close()
## Return a success message
return jsonify({'message': 'User deleted successfully'})
This endpoint is used to delete a user from the "users" table. We use the execute()
method to delete the user from the "users" table.
Finally, let's add the following code to run the Flask application:
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=8080)