Open In App

How to Create a Flask API with MariaDB on AWS EC2

Last Updated : 08 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, We are going to create an ec2 instance, install a MySQL database using MariaDB on the ec2 instance, and create an API of Login using the flask python framework. Flask is a micro web framework written in Python. MariaDB is one of the most popular open-source relational database management systems and could be used as a great replacement for MySQL. AWS ec2 instance allows users to rent virtual computers on which to run their computer applications, installing and Running MYSQL on EC2 Server(Linux)

Step-by-Step Guide for Creating Flask API with MariaDB on EC2

Step 1: Signing In

Sign in to your Management Console. Go to EC2.

Step 2: Launching Instance

Click on the “Instances” section in the left sidebar. Click the “Launch Instance” button to start the instance creation process.

Launch Instance

Then enter the appropriate Name of instance, for example MyInstance and select instance type as Amazon Linux 2 AMI(HVM) -Kernel 5.10, SSD volume Type in Application and OS Images. Select t2.micro as instance type.

Step 3: Creating Key Pair(.pem)

Choose an existing key pair if you have one, or create a new one. If you create a new key pair, make sure to download the private key file (.pem) and store it securely.

Step 4: Configuration to Launch Instance

Create a new security group or choose an existing one. Open ports for SSH (22), HTTP (80), Custom TCP(8080) to Run Flask API, MySQL/Aurora(3306). Review your settings and launch the Instance by clicking the Launch Instance Button

Launch Instance Success

Step 5: Connecting to Instance

We can see our Instance (MyInstance) in EC2 instance Dashboard. Select the check box of our Instance and go to Action and click on Connect to Connect the Instance.

Connect Instance

Step 6: Checking Python Version

Enter the following command in the console to check the Python Version.

python3 --version

if Python is not installed then enter following command.

sudo apt-get install python3

Step 7: Installing MariaDB Server

Run the following command for installing mariadb-server

sudo yum install -y mariadb-server

MariaDB Installation

This command will install the MariaDB server.

After install MariaDB server start using

sudo systemctl start mariadb

Use this command for start MariaDB service automatically

sudo systemctl enable mariadb

Start MariaDB

Step 8: Accessing MariaDB Shell

Access the MariaDB shell

mysql -u root

create a new database for your Flask app using SQL commands

CREATE DATABASE mydb

Use the new created Database and create a Table using SQL command

CREATE TABLE users (id INT PRIMARY KEY, username VARCHAR(20), password VARCHAR(20))

To Insert Data in Table using SQL command

INSERT INTO users (username, password) VALUES ('Harsh', 'Harsh'), ('Ram', 'Ram')

Accessing MariaDB Shell

Step 9: Save Flask App

After exiting from MySQL and Create a Directory to save your Flask app code and its related file.

mkdir Web
cd Web

Step 10: Setup Flask Environment

Setup Flask environment, For creating virtual environment

python3 -m venv exflask

Activate the virtual environment

source exflask/bin/activate

Step 11: Install Flask Package using pip

Install the Flask package using pip

pip3 install Flask

Install Flask

This command install the Flask package, which help us to create an web application in python.Access the mysql in your flask app to install flask-mysqllab package.

pip3 install Flask-MySQLdb

.If you get an error like this.

Error

We have to Install some dependencies to avoid the error.

 “pip install mysqlclient>=1.3.7

These commands install necessary dependencies allow to the “mysqlclient” package to Flask app.

Step 12: Writing Code for Flask App

Leat’s create Flask app.

touch app.py

This command creates an empty file which contains your Flask application code.

To write your application code in app.py file ,Using

nano app.py

This command opens the app.py file in the nano editor, you write and edit your code hear.

Inside the ‘app.py file, you’ll write your Flask application code.

Python




from flask import Flask, render_template, request, redirect, url_for
from flask_mysqldb import MySQL
app = Flask(__name__)
  
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'mydb'
  
mysql = MySQL(app)
  
  
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        uname = request.form['uname']
        pas = request.form['pas']
  
        mysql_cur = mysql.connection.cursor()
        query = "SELECT * FROM users WHERE username = "+uname
        mysql_cur.execute(query)
        user_info = mysql_cur.fetchone()
        mysql_cur.close()
  
        if user_info and user_info[2] == pas:
            return "Login successful!"
        else:
            return "Login failed. Please try again."
  
    return render_template('login.html')
  
  
app.run(host='0.0.0.0', port=8080)


Step 13: Creating Templates

Inside your main project directory create a subdirectory named “templates”

mkdir templates && cd templates

Within the “templates” directory, create a new HTML file named login.html

touch login.html

This command creates an empty login.html file, which you’ll write your login page code.

nano login.html

Inside the ‘login.html’ file, paste the following HTML code to define the structure of your login page template

HTML




<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <h1>Login Page</h1>
    {% if error_message %}
    <p>{{ error_message }}</p>
    {% endif %}
    <form method="POST">
        <label for="username">Username:</label>
        <input type="text" id="uname" name="uname"><br><br>
        <label for="password">Password:</label>
        <input type="password" id="pas" name="pas"><br><br>
        <input type="submit" value="Login">
    </form>
</body>
</html>


Step 14: Running Flask App

Navigate to Your main Project Directory ‘Web’ and Run Your Flask App

python3 app.py

This command starts the Flask development server

Flask Development Initializtion

Open your browser and open AWS console navigate EC2 and select your instance public IP copy it and past it in URL and at last add “:8080” to access our flask app (ec2-public-ip:8080).

20

For going Login page write

“(ec2-public-ip:8080/login”

19

Enter a username and password to test the login functionality.

21

FAQs OnCreate a Flask API with MariaDB on AWS EC2

1. What Is Flask?

Flask is a web application framework written in Python. It was developed by Armin Ronacher, who led a team of international Python enthusiasts called Poocco. Flask is based on the Werkzeg WSGI toolkit and the Jinja2 template engine.Both are Pocco projects.

2. What is API?

API is the acronym for application programming interface — a software intermediary that allows two applications to talk to each other.

3. What is MariaDB?

MariaDB is an open source relational database management system (DBMS) that is a compatible drop-in replacement for the widely used MySQL database technology.

4. Use of Flask?

Flask is a small and lightweight Python web framework that provides useful tools and features that make creating web applications in Python easier.

5. Why API are used?

APIs are used to integrate new applications with existing software systems. This increases development speed because each functionality doesn’t have to be written from scratch. You can use APIs to leverage existing code.



Similar Reads

How To Configure Flask API To Your Domain Name On AWS EC2?
In this article, We are going to create a Flask API on an EC2 Instant and we will learn how to configure it with a domain name using Gunicorn and nginx(NGINX). Flask is a web microframework, it’s a Python module that lets you develop web applications easily. A domain name is a string of text that maps to an alphanumeric IP address, used to access a
8 min read
How To Create Spot Instance In Aws-Ec2 In Aws Latest Wizards?
Spot instances are available at up to 90% discount because when instances are not used then the instance available in spot instance at a cheaper rate so that people can utilize. it. When the demand increases then amazon sent a notification your spot instance will disappear after two minutes. We can use it for temporary work if our data losses it wi
6 min read
How To Use AWS EC2, EBS, and S3 Services Using AWS CLI?
AWS CLI is a command line tool that is used for managing the AWS Services from the command line. On downloading the AWS CLI software and configuring it with your AWS credentials you can control the AWS services from the command line and can automate the work through scripts. Whether you are launching EC2 instances, attaching the EBS Volumes, or man
12 min read
Create an EC2 Instance With EC2 User Data Script To Launch Website
Amazon EC2 is one of the most popular AWS offerings. It stands for Elastic Compute Cloud. This is the way to do Infrastructure as a Service on AWS. EC2 is not just one service. It's composed of many things at a high level. You can rent virtual machines on EC2, they're called EC2 instances.You can store data on virtual drives or EBS volumes.You can
9 min read
How to Install Python3 on AWS EC2?
AWS or Amazon web services is a cloud service platform that provides on-demand computational services, databases, storage space, and many more services. EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we
3 min read
Launching AWS EC2 Instance using Python
In this article, we will learn how python can be used for creating and managing Amazon Web Services (AWS) such as Elastic Compute Cloud (EC2), Simple Storage Service (S3), Relational Database Service (RDS). For this purpose, we will use boto3 library of python, Boto is a Python package that provides interfaces to Amazon Web Services (AWS). Prerequi
4 min read
Connecting an AWS EC2 Instance of a Private Subnet using Bastion Host
In this article, we will see how we can connect an instance present in a private subnet with the help of an instance present in a public subnet. Let us first have look over the following mentioned Key terminologies where we will first try to understand few things (like EC2 instance and other things) theoretically and then we will jump into the impl
8 min read
How to Install Go on AWS EC2?
EC2 or Elastic Compute Cloud is a scalable computing service launched on the AWS cloud platform. In simpler words, EC2 is nothing but a virtual computer on which we can perform all our tasks and we have the authority to configure, launch or even dissipate this virtual computer.Go is an open-source, statically typed, compiled programming language de
2 min read
Launch the EC2 Instance in AWS with New Instance Wizard
Pre-requisite:- EC2 EC2 stands for Elastic Compute Cloud and it is an AWS web service for on-demand computing service. It is based on the pay-as-you-go model. We can create instances anytime from anywhere via the internet. We can easily create the instance or terminate the instance within minutes with our required operating system. we can configure
2 min read
AWS EC2 On Demand and Spot Instances
In this article, we are going to understand difference between EC2 On demand and Spot instances. We are going to learn their usage and working. it is important to understand the difference between AWS EC2 On Demand and Spot Instances so that you can choose right instances for your business requirement. AWS EC2 (Elastic Compute Cloud) is a cloud com
6 min read
Practice Tags :